<?php 
/**
 * Repair center controller contails all the functions for our phone repair service
 * All the function in the shop generally run in shop
 * All the funciton in repair parts generally for warehouse 
 * @author Norman
 *
 */
class RepaircenterController extends Zend_Controller_Action
{

	public static $rCenterMapping;
	public static $rCenterMappingReserve = array(
			1 => array("BSXP","BSPC","BSIC"),
			2 => array("CSIC"),
			3 => array("WHBN"),
			4 => array("BHPC"),
			5 => array("HPIC"),
			6 => array("CBPC","CBIC"),
			7 => array("WLIC"),
			8 => array("EPIC"),
			9 => array("WBPC","WBIC"),
		   10 => array("NLPC"),
		   11 => array("DCIC"),
		   12 => array("KCPC"),
		   13 => array("SLIC"),
		   14 => array("FGIC"),
		   15 => array("PMIC","PMPC"),
		   16 => array("WGIC","WGPC"),
		   17 => array("ADPC"),
		   18 => array("BBPC"),
		   19 => array("CLPC","CLIC"),
		   20 => array("WHLU"),
		   21 => array("BSIC"),
		   23 => array("WHAL"),
		   30 => array("HPPC"),
		   24 => array("JASON")										
		);
	
    public function init(){
    /**
	 *
	 *
	 */    
    	self::$rCenterMapping = unserialize(ARR_RCENTER_MAPPING);
	}
	
	/**
	 * This is the landing page of repair center 
	 */
    public function indexAction(){
	
		echo "Repair Center Controller";	

	}
	
	/**
	 * This is the main page for each shop 
	 * it has been renewed and contains 21 functions 
	 * of all shop needed function 
	 */
	public function mainpageAction(){

		$shopHead = $this->_getParam('shop');
		$shopName = "";
		
		
		if($shopHead!="" && $shopHead != "WHCH"){
				
			$shops = new Model_DbTable_Shoplocation();
			$shopName = $shops->getNameByHead($shopHead);
			
			if($shopName){
				$this->view->shophead = $shopHead;
				$this->view->shopname = $shopName;
				$this->view->rCenterMapping  = self::$rCenterMapping;
				$this->view->check = true;
			}else{
				$this->view->check = false;
			}
			
		}
		
		
		
		
		//echo "This is main choose page";
		
	
			
		$this->renderScript("/repaircenter/mainpage20140716.phtml");	

	}

	/**
	 * Create new job function , this function has been recenterly 
	 * updated, for HPIC , it has the function of glass only
	 */
	public function newAction(){
		
		$shopHead = $this->_getParam('shop');
		if($shopHead == "" or strlen($shopHead)!= 4 ){
			
			$this->_redirect("/repaircenter/");
				
		}
		$shopName = "";
		$this->view->shophead = $shopHead;
		
		date_default_timezone_set('Australia/Melbourne');
		$jobIdDate = intval(date("Ymd"));
		
		$jobIdCounter = new Model_DbTable_Jobidcounter();
		
		$repairJob = new Model_DbTable_Repairjob();
		
		$newCounter = $jobIdCounter->runCounter();
		
		$newJobID = $jobIdDate*100000 + $newCounter;	
		//d($newJobID);
		
		$this->view->newjobid = $newJobID;	

			if($shopHead == "HPIC"){
				
				$this->renderScript("/repaircenter/new20150210.phtml");
			}else{
				$this->renderScript("/repaircenter/new20150727.phtml");
			}
			
	}
	/**
	 * API function for fill in information if creat as quick form job
	 @author leo
	 */
	public function editAction(){
		$jobHead = $this->_getParam('jobId');
		$repairJob = new Model_DbTable_Repairjob();
		$repairRecord = new Model_DbTable_Repairstatusrecord();
		
		if($jobHead==""){
			return false;
		}
		
		$repairJobDetail = $repairJob->getJob($jobHead);
		$repairJobStatus = $repairRecord->getLastStatus($jobHead);
		if($repairJobDetail['is_qf']==1){
			$this->view->repairjobDetail = $repairJobDetail;
		}elseif($repairJobStatus[0]['id_status'] < 90){
			$this->view->repairjobDetail = $repairJobDetail;
		}else{
			$this->view->errorFlag = true;
			$this->view->errorMessage = "This is not the quick form job, you cannot edit it.";
		}
	}
	
	/**
	 * This is the page to print 3 section of the confirm quote 
	 * customer section 
	 * shop sectoin and repair staff section 
	 */
	public function confirmquoteAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		$dateToday = date("Y-m-d");
		$timeNow = date(" H:i");
		$repairJob = new Model_DbTable_Repairjob();
		$shopCode = $this->_getParam('shop');
		$newJobID = $this->_getParam('newjobid');
		$staffName = $_POST['staff_name'];
		$dateStart = $dateToday;
		$timeStart = $timeNow;
		$brand = $_POST['mobile_brand'];
		$model = $_POST['mobile_model'];
		if($model == "Not In The List"){
			$model =  $_POST['mobile_model_other'];
		}
		$imei = $_POST['mobile_imei'];
		$onScreenImei = $_POST['onscreenImei_check'];
		//$partsSelection =  $_POST['parts_select'];
		$partsSelection = "parts";
		$repairType = implode(",",$_POST['repair_type']);
		$inspectionOption = $_POST['inspection'];
		$issueDetail = $_POST['issue_detail']; //inspection Detail
		$cname = $_POST['customer_name'];
		$cemail = $_POST['customer_email'];
		$cphone = $_POST['customer_homephone'];
		$cmobile = $_POST['customer_mobile'];
		$quoteChoice = $_POST['quot_choice'];
		$price = $_POST['quot_price'];
		$invoice = $_POST['quot_invoice'];
		$passcode = $_POST['mobile_passcode'];
		$color = $_POST['mobile_color'];
		$pickup = $_POST['pickup_detail'];
		$warrTerm = $_POST['warr_term'];
		$extWarr = $_POST['ext_warr'];
		$warrPrice = $_POST['warr_price'];
		$noImeiReason = $_POST['no_imei_reason'];
		$screenwork = $_POST['screen_work'];
	
		//add into DB
		if($imei == null){
			$errorFlg = false;
			$this->view->newjobid = $newJobID;
			$this->view->errorflag = $errorFlg;
			$this->view->shopcode = $shopCode;
			$this->view->staffname = $staffName;
			$this->view->datetime = $dateToday.$timeNow;
			$this->view->brand = $brand;
			$this->view->model = $model;
			$this->view->imei = $imei;
			$this->view->partsselection = $partsSelection;
			$this->view->repairtype = $repairType;
			$this->view->issuedetail = $issueDetail;
			$this->view->inspectionOption = $inspectionOption;
			$this->view->cname = $cname;
			$this->view->cemail = $cemail;
			$this->view->cphone = $cphone;
			$this->view->cmobile = $cmobile;
			$this->view->quotechoice = $quoteChoice;
			$this->view->price = $price;
			$this->view->invoice = $invoice;
			$this->view->passcode = $passcode;
			$this->view->color = $color;
			$this->view->pickupdetail = $pickup;
			$this->view->warrTerm = $warrTerm;
			$this->view->extWarr = $extWarr;
			$this->view->warrPrice = $warrPrice;
			$this->view->screenwork = $screenwork;
			return false;
		}
	
		$errorFlg = true;
		$errorFlg = $repairJob->addJob($newJobID, $shopCode, $staffName, $dateStart, $timeStart, $brand, $model, $imei, $partsSelection, $repairType, $issueDetail, $cname, $cemail, $cphone, $cmobile, $price, $invoice,$passcode,$color,$pickup,$warrTerm,$extWarr,$warrPrice,$noImeiReason,$screenwork,$inspectionOption);
	
		$transRecord = new Model_DbTable_Pr_Transrecord();
		$transRecord->addTransrecord($newJobID, $shopCode,110, $dateStart, $dateStart.' '.$timeStart,null,"Job Created By ".$staffName,-1);
	
	
		if($onScreenImei == $imei){
			$repairJob->updateOnScreenImei($newJobID, $imei);
		}
		//INITIAL STATUS
	
		if($model == "iPod Touch 3" || $model=="iPod Touch 4" || $model=="iPod Touch 5" || $model=="iPod Touch 6" || $model=="iPad 2" || $model=="iPad 3" || $model=="iPad 4" || $model=="iPad 5" || $model=="iPad Mini"  || $model=="iPad Air" ){
			$repairJob->updateOnScreenImei($newJobID, $imei);
	
		}
	
		$statusRecord = new Model_DbTable_Repairstatusrecord();
	
		$idQuoteChoice = 3;
	
		if($quoteChoice == "instant"){
			 
			$idQuoteChoice =1;
		}
	
		$statusRecord->insertStatus($newJobID,$idQuoteChoice,$dateToday.$timeNow,$staffName);
	
		//pass to the view
	
		$this->view->newjobid = $newJobID;
		$this->view->errorflag = $errorFlg;
		$this->view->shopcode = $shopCode;
		$this->view->staffname = $staffName;
		$this->view->datetime = $dateToday.$timeNow;
		$this->view->brand = $brand;
		$this->view->model = $model;
		$this->view->imei = $imei;
		$this->view->partsselection = $partsSelection;
		$this->view->repairtype = $repairType;
		$this->view->inspectionOption = $inspectionOption;
		$this->view->issuedetail = $issueDetail;
		$this->view->cname = $cname;
		$this->view->cemail = $cemail;
		$this->view->cphone = $cphone;
		$this->view->cmobile = $cmobile;
		$this->view->quotechoice = $quoteChoice;
		$this->view->price = $price;
		$this->view->invoice = $invoice;
		$this->view->passcode = $passcode;
		$this->view->color = $color;
		$this->view->pickupdetail = $pickup;
		$this->view->warrTerm = $warrTerm;
		$this->view->extWarr = $extWarr;
		$this->view->warrPrice = $warrPrice;
		$this->view->screenwork = $screenwork;
		
		if($screenwork == 10){
			$this->renderScript("/repaircenter/confirmquote_glassonly.phtml");
		}
				
	}

	/**
	 * This is link in the status page 
	 * when update the quote , you need to fill in the second invoice 
	 */
	
	public function updatequoteAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		$dateToday = date("Y-m-d");
		$timeNow = date(" H:i");
		$repairJob = new Model_DbTable_Repairjob();
		$shopCode = $this->_getParam('shop');
		$newJobID = $this->_getParam('jobid');
		$staffName = $_POST['staff_name'];
		$dateStart = $dateToday;
		$timeStart = $timeNow;
		$brand = $_POST['mobile_brand'];
		$model = $_POST['mobile_model'];
		if($model == "Not In The List"){
			$model =  $_POST['mobile_model_other'];
		}
		$imei = $_POST['mobile_imei'];
		//$partsSelection =  $_POST['parts_select'];
		$partsSelection = "parts";
		$repairType = implode(",",$_POST['repair_type']);
		$issueDetail = $_POST['issue_detail'];
		$inspectionOption = $_POST['inspection'];
		$cname = $_POST['customer_name'];
		$cemail = $_POST['customer_email'];
		$cphone = $_POST['customer_homephone'];
		$cmobile = $_POST['customer_mobile'];
		$quoteChoice = $_POST['quot_choice'];
		$price = $_POST['quot_price'];
		$invoice = $_POST['quot_invoice'];
		$passcode = $_POST['mobile_passcode'];
		$color = $_POST['mobile_color'];
		$pickup = $_POST['pickup_detail'];
		$warrTerm = $_POST['warr_term'];
		$extWarr = $_POST['ext_warr'];
		$warrPrice = $_POST['warr_price'];
		$noImeiReason = $_POST['no_imei_reason'];
		$screenwork = $_POST['screen_work'];
		//add into DB
		$errorFlg = true;

		$rJob = $repairJob->getJob($newJobID);
		
		
		$errorFlg = $repairJob->updateJob($newJobID, $shopCode, $staffName, $dateStart, $timeStart, $brand, $model, $imei, $partsSelection, $repairType, $issueDetail, $cname, $cemail, $cphone, $cmobile, $price, $invoice,$passcode,$color,$pickup,$warrTerm,$extWarr,$warrPrice,$noImeiReason,$screenwork,$inspectionOption);
		//INITIAL STATUS
		
		if($model == "iPod Touch 3" || $model=="iPod Touch 4" || $model=="iPod Touch 5" || $model=="iPod Touch 6" || $model=="iPad 2" || $model=="iPad 3" || $model=="iPad 4" || $model=="iPad 5" || $model=="iPad Mini"  || $model=="iPad Air" ){
			$repairJob->updateOnScreenImei($newJobID, $imei);
		
		}
		//pass to the view

			$this->view->newjobid = $newJobID;
			$this->view->errorflag = $errorFlg;
			$this->view->shopcode = $shopCode;
			$this->view->staffname = $staffName;
			$this->view->datetime = $dateToday.$timeNow;
			$this->view->brand = $brand;
			$this->view->model = $model;
			$this->view->imei = $imei;
			$this->view->partsselection = $partsSelection;
			$this->view->repairtype = $repairType;
			$this->view->issuedetail = $issueDetail;
			$this->view->inspectionOption = $inspectionOption;
			$this->view->cname = $cname;
			$this->view->cemail = $cemail;
			$this->view->cphone = $cphone;
			$this->view->cmobile = $cmobile;
			$this->view->quotechoice = $quoteChoice;
			$this->view->price = $price;
			$this->view->invoice = $invoice;
			$this->view->passcode = $passcode;
			$this->view->color = $color;
			$this->view->pickupdetail = $pickup;
			$this->view->screenwork = $screenwork;
			$this->view->warrTerm = $warrTerm;
			$this->view->extWarr = $extWarr;
			$this->view->warrPrice = $warrPrice;

	}
	
	/**
	 * this is the function for shop to show the currently opeing job 
	 * @return boolean
	 */		
	public function showstatusAction(){
		
		$arrBuddyShop = array(
			"BSPC" => array("BSIC","BSXP"),	
			"BSIC" => array("BSPC","BSXP"),
			"BSXP" => array("BSPC","BSIC"),
			"CLPC" => array("CLIC"),
			"CLIC" => array("CLPC"),
			"PMPC" => array("PMIC"),
			"PMIC" => array("PMPC"),	
			"WBPC" => array("WBIC"),
			"WBIC" => array("WBPC"),
			"WGPC" => array("WGIC"),
			"WGIC" => array("WGPC"),
			"CBPC" => array("CBIC"),
			"CBIC" => array("CBPC")				
				);
		
		$shopHead = $this->_getParam('shop');
		$show = "";
		if($shopHead == "BSPC" || $shopHead == "BSIC" || $shopHead == "BSXP" || $shopHead == "CLPC" || $shopHead == "CLPC" || $shopHead == "PMPC"
		 ||	$shopHead == "PMIC" || $shopHead == "WBPC" || $shopHead == "WBIC" || $shopHead == "WGPC" || $shopHead == "WGIC" || $shopHead == "CBIC" || $shopHead == "CBPC")
		{
			$show = "buddy";
		}
		$repairJob = new Model_DbTable_Repairjob();
		//2014-07-30
		$quickJobs = $repairJob->getQuickJobbyshop($shopHead);
		$searchResult = $repairJob->listUnfinishedJobByShop($shopHead);
		$openJobs = $repairJob->currentOpenJobList($searchResult);
		if($show == "buddy"){
			$searchResult = $repairJob->listUnfinishedJobByShopMultiShopView($shopHead, $arrBuddyShop[$shopHead]);
			$openJobs = $repairJob->currentOpenJobListMultiShop($searchResult);
		}
		$this->view->shophead = $shopHead;
		$this->view->searchresult = $searchResult;
		$this->view->rCenterMapping  = self::$rCenterMapping;
		$this->view->openJobs = $openJobs;
		$this->view->quickJobs = $quickJobs;
		if(isset($_POST['emergency_button'])){
		
			foreach($_POST['emergency_button'] as $k => $v){
				$idJob = $_POST['id_job2'][$k];
				//$repairStaff = $_POST['repair_staff'][$k];
				$this->view->jobId = $idJob;
				$this->view->shopHead = $shopHead;
				$this->renderScript("repaircenter/emergency-staff-record.phtml");
				return true;
			}
				
		}
		
		if($show == "buddy"){
			$this->renderScript("repaircenter/showstatus_buddy.phtml");
		}
		//2014-07-18
		
	}
	/**
	 * For handle who change the job to emergency job 
	 * @version 2014-07-21
	 * @author Leo
	 */
	public function emergencyStaffRecordAction(){
		if($_POST['button']){
			$idJob = $_POST['job_id'];
			$shopHead = $_POST['shop_name'];
			$levelDays = $_POST['lv_day'];
			$deliveryOption = $_POST['delivery'];
			$detail = $_POST['detail'];
			$sDetail = new Model_DbTable_Roster_Stafflogindetail();
			$repairJob = new Model_DbTable_Repairjob();
			$idStaffRow = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST["password"])));
			$mail = new Model_Emailshandler();
			$mailAdd = array('office@phonecollection.com.au','simon.phonecollection@gmail.com','phonecollection.au@gmail.com');
			$jobStatus = new Model_DbTable_Repairstatusrecord(Zend_Registry::get('db_default'));
			
			date_default_timezone_set('Australia/Melbourne');
			$datechange = date("Y-m-d H:i");
			if($idStaffRow != null){
				$jobDetail = $repairJob->getJob($idJob);
				$str = 'The job as below has change to emergency job, please follow the process to confirm it can be done in 7 days'.'<br/>'.'Job ID:'.$idJob.'<br/>'.'Update Staff:'.$idStaffRow['ni'].'<br/>'.'Shop:'.$jobDetail['shop_code'].'<br/>'.'Brand&Model:'.$jobDetail['mobile_brand'].',  '.$jobDetail['mobile_model'].'<br/>';
				foreach($mailAdd as $k2 => $v2){
					$mail->sendNormalEmail($v2, 'Job ID:'.$idJob.' status has changed to emergency job.', $str);
				}
				$repairJob->updateEmergencyJobInfo($idJob, $levelDays, $deliveryOption, $detail);
				$jobStatus->insertStatus($idJob,36, $datechange, $idStaffRow['ni']);
				$url2 = "/repaircenter/showstatus/shop/{$shopHead}";
				$this->_redirect($url2);

			}else{
				$this->view->errorflag = true;
				$this->view->errorMessage = "Password is not correct, please try again.";
				return false;
			}

		}
	}
	
	/**
	 * this is the function in the main page search bar 
	 * it search the job id /IMEI / device id (only for apple )
	 */
	public function showstatusbyjobidAction(){
	
		$shopHead = $_POST['shop_head'];
		$idJob = $_POST['id_job'];
		$repairJob = new Model_DbTable_Repairjob();
		$searchResult = "";
	
		if(!is_numeric($idJob)){
			$searchResult = $repairJob->getJobIdByIMEI($idJob);
		}
		else{
			
			$searchResult = $repairJob->listAllJobById($idJob);
			if(!$searchResult){
				
				$searchResult = $repairJob->getJobIdByIMEI($idJob);
			}
			if($searchResult[0]['is_qf'] == 1){
				$url2 = "/repaircenter/edit/jobId/{$searchResult[0]['id_job']}";
				$this->_redirect($url2);
			}
		}
		
		$this->view->shophead = $shopHead;
		//var_dump($searchResult);
		$this->view->searchresult = $searchResult;
		$this->view->rCenterMapping  = self::$rCenterMapping;
	}	
	
	/**
	 * This is the function for warehouse to check all the job status 
	 */
	public function showallstatusAction(){
		
		$repairJob = new Model_DbTable_Repairjob();
		
		$searchResult = $repairJob->listAllUnfinishedJobs();
		//var_dump($searchResult);
		$this->view->searchresult = $searchResult;		
		
	}

	/**
	 * This is the function to check all the finished job 
	 */
	public function showallhistoryAction(){
	
		$shopHead = $this->_getParam("shop");
		
		$repairJob = new Model_DbTable_Repairjob();
		
		$searchResult =($shopHead=="ALL")?$repairJob->listAllfinishedJobs():$repairJob->listAllfinishedJobsByShop($shopHead);
		//var_dump($searchResult);
		$this->view->searchresult = $searchResult;
	
	}
	
	public function warrantyAction(){
		$idJob = $this->_getParam('idJob');
		$shophead = $this->_getParam('shophead');
		$repairJob = new Model_DbTable_Repairjob();
		$stInfo = new Model_DbTable_Roster_Stafflogindetail();
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$rJob = $repairJob->getJob($idJob);
		$wStartDate = "";
		
		$this->view->idJob = $idJob;
		$this->view->shophead = $shophead;

			if($rJob['invoice_no']){
				$inv1 = "L1".substr($rJob['invoice_no'],-8);

				$shop = $rJob['shop_code'];
			
				$dateCheck = "20".substr($rJob['invoice_no'],-9,-3);
				$warrantyDay = $rJob['warranty_term'] + $rJob['extended_warranty'];
				
				if($dateCheck == Model_DatetimeHelper::dateToday("")){
					$this->view->message = "Job Create Date: ".$dateToday."<br/>"."Warranty Term: $warrantyDay"."<br/>"."Warranty Status: Within Warranty";
					$this->view->check = true;
				}else{
				$date1 = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/online-invoice-date/shop/".$shop."/inv/".$inv1);
			
				if($date1 != 0){
					
					$wdLine1 = Model_DatetimeHelper::adjustDays('add', $date1, $warrantyDay);

				}
			
				if($rJob['invoice_no2']){
					$inv2 = $rJob['invoice_no2'];
					$date2 = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/online-invoice-date/shop/".$shop."/inv/".$inv2);
					if($date2 != 0){
						$wdLine2 = Model_DatetimeHelper::adjustDays('add', $date2, $warrantyDay);
					}
				}	
				
				if($date1 > $date2){
					$wStartDate = $date1;
				}else{
					$wStartDate = $date2;
				}
			
				if($wdLine1 > $dateToday || $wdLine2 > $dateToday){
					$this->view->message = "Job Create Date: ".$wStartDate."<br/>"."Warranty Term: $warrantyDay"."<br/>"."Warranty Status: Within Warranty";
					$this->view->check = true;

				}else{
					$this->view->message = "Job Create Date: ".$wStartDate."<br/>"."Warranty Term: $warrantyDay"."<br/>"."Warranty Status: Without Warranty"."<br/> You can continue, but if manager not approve, you will not get bonus";
					$this->view->check = false;
				
				}
				}
			
			}else{
				$this->view->message = "No Invoice, cannot check warranty <br/> You can continue, but if manager not approve, you will not get bonus";
				$this->view->check = false;

			}
		
		
		if(isset($_POST['submit'])){
			$password = $_POST['password'];
			$part = $_POST['part'];
			$shopCode = unserialize(ARR_RCENTER_MAPPING);
			$rProducts = new Model_DbTable_Pr_Prproducts();
			
			if($password == 'pass'){
								
				$desRow = $rProducts->getProductDes($part);
					
				$this->view->idShop = $shopCode[$rJob['shop_code']];
				$this->view->shopHead = $rJob['shop_code'];
				$this->view->faultyBarcode = $part;
				if(!$desRow){
					$this->view->faulty_des = "<span style=\"color:red;\">Error Occur,BarCode Not Exist</span>";
				}
				else{
					$this->view->faulty_des =$desRow;
				}
				$this->view->pass = 'nosc';
				$this->renderScript('repaircenter/warranty-rma.phtml' );

			}else{
				$desRow = $rProducts->getProductDes($part);
				$this->view->idShop = $shopCode[$rJob['shop_code']];
				$this->view->shopHead = $rJob['shop_code'];
				$this->view->faultyBarcode = $part;
				$this->view->pass = 'sc';
				if(!$desRow){
					$this->view->faulty_des = "<span style=\"color:red;\">Error Occur,BarCode Not Exist</span>";
				}
				else{
					$this->view->faulty_des =$desRow;
				}
				$this->renderScript('repaircenter/warranty-rma.phtml' );
			}
			
		}
		
	}
	
	public function warrantyConfirmAction(){
		$manager = unserialize(ARR_MANAGER);
		$rJob = new Model_DbTable_Repairjob();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$mgr = $this->_getParam("mgr");
		$jobList = array();
		$jobHistory = array();
		
		
		if(isset($_POST['submit'])){
			$password = $_POST['password'];
			$idCheck = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($password));
			
			if($idCheck){
				if($manager[$idCheck['id']]){
					$url = "/repaircenter/warranty-confirm/mgr/".$idCheck['id'];
					$this->_redirect($url);
				}else{
					echo '<script language="javascript"> window.alert("You are not a manager")</script>';
				}
			}else{
				echo '<script language="javascript"> window.alert("Incorrect Password, Please try your password again")</script>';
			}
		}
		
		if(isset($_POST['accept']) || isset($_POST['reject'])){
			 if(!empty($_POST['accept'])){
			 	$idJob = key($_POST['accept']);
			 	$reason = $_POST['reason'][key($_POST['accept'])];
			 	$rJob->updateWarrantyCheck($idJob, 'inwarranty');
			 	if(!empty($reason)){
			 		$rJob->updateWarrantyReason($idJob, $reason);
			 	}
			 }
			 
			 if(!empty($_POST['reject'])){
			 	$idJob = key($_POST['reject']);
			 	$reason = $_POST['reason'][key($_POST['reject'])];
			 	$rJob->updateWarrantyCheck($idJob, 'rejectwarranty');
				if(!empty($reason)){
			 		$rJob->updateWarrantyReason($idJob, $reason);
			 	}
			 }
		}
		
		if(!empty($mgr) && $manager[$mgr]){
			foreach ($manager[$mgr] as $k => $v){
				$jobList[$v] = $rJob->listAllWarrantyJobByShop($v,1);
				$jobHistory[$v] = $rJob->listAllWarrantyJobByShop($v,2);
			}
		}

		$this->view->jobList = $jobList;
		$this->view->jobHistory = $jobHistory;
	}
	
		
	/**
	 * Check job detail according the staff filled in 
	 * this function is replaced by view details status
	 */
	public function viewdetailAction(){
		
		$jobid = $this->_getParam('jobid');
		$repairJob = new Model_DbTable_Repairjob();
		$this->view->jobdetail = $repairJob->getJob($jobid);

		
	}
	/**
	 * This will not only show the job detail 
	 * it also shows the status history , by checkging the history the staff know what had happpend
	 */
	public function viewdetailstatusAction(){
		
		$jobid = $this->_getParam('jobid');
		
		if(isset($_GET['jid'])){
			$jobid = $_GET['jid'];
		}
		$repairJob = new Model_DbTable_Repairjob();
		$this->view->jobdetail = $repairJob->getJob($jobid);
		
		$statusRecords = new Model_DbTable_Repairstatusrecord();
		$recordsList = $statusRecords->getStatusList($jobid);
		
		$this->view->list = $recordsList;
		
		$commentRecords = new Model_DbTable_Jobcomments();
		$commentList = $commentRecords->listCommentByJobID($jobid);		
		$this->view->commlist = $commentList;
		
	}
	/**
	 * this is the individual history status page
	 */
	public function viewhistoryAction(){
		$idJob = $this->_getParam('jobid');
		$statusRecords = new Model_DbTable_Repairstatusrecord();
		$recordsList = $statusRecords->getStatusList($idJob);
		
		$this->view->list = $recordsList;
		
	}
	/**
	 * this is the fucntion to change the status 
	 * this function is for warehouse not for shop 
	 * this function can change status without any checking 
	 * if the item do not have imei or anything else
	 * you need to using this funtion to help shop to close the job
	 * 	 
	 */
	public function changestatusAction(){
		
		$idJob = $this->_getParam('jobid');
		
		$this->view->resultmessage ="";
		date_default_timezone_set('Australia/Melbourne');
		$dateTime = date("Y-m-d H:i");
		
		$statusRecord = new Model_DbTable_Repairstatusrecord();
		$rjob = new Model_DbTable_Repairjob();
		
		$this->view->currentstatus = $statusRecord->getLastStatus($idJob);
			
		if($_POST){
			
			if($_POST['staff_name']==""){
				
				$this->view->resultmessage = "<span style=\"color:#FF0000;\">You Must input your Name, Record did not Save</span>";
			}
			else{
				//$statusRecord->insertStatus($idJob, $idStatus, $timeRecord, $staffRecord)
				if($_POST['id_status'] != 9999 ){
				$statusRecord->insertStatus($_POST['job_id'],$_POST['id_status'],$dateTime,$_POST['staff_name']);
				}
				else{
					$statusRecord->insertStatus($_POST['job_id'],90,$dateTime,$_POST['staff_name']);
					$rjob->addFixbyHqStatus($_POST['job_id'],"Job Close By HQ, NO Bonus");
					
				}
				$this->view->resultmessage = "<span  style=\"color:#009900;\">Status Successfully Saved! You can Not Close this Page</span>";
			}
			
		}
					
	}
	/**
	 * this is shop change status page 
	 * it has all conditions to close the job 
	 * there should be repair by 
	 * there should be invoice 
	 * if the quotation changed there should be two invoice
	 * there should be on screen IMEI
	 * @todo when change status , it need password instead of Name
	 */
	public function changestatusshopAction(){
	
		$idJob = $this->_getParam('jobid');
	
		$this->view->resultmessage ="";
		date_default_timezone_set('Australia/Melbourne');
		$dateTime = date("Y-m-d H:i");
	
		$statusRecord = new Model_DbTable_Repairstatusrecord();
		
		$transRecord = new Model_DbTable_Pr_Transrecord();
		$lastRecord = $transRecord->getLastJobLocation($idJob);
		
		$rJob = new Model_DbTable_Repairjob();
		
		$repairStaff = $rJob->getRepairStaff($idJob);
		$rJobDetail = $rJob->getJob($idJob);
		if($repairStaff==0 || $repairStaff==null || $repairStaff==""){
			
			$this->view->repairStaffRecord = true;
		}
		else{
			$this->view->repairStaffRecord = false;
		}
		$jobStatusList = $statusRecord->getStatusList($idJob);
		$jobLastStatus = $statusRecord->getLastStatus($idJob);
		
		if(!empty($jobStatusList)){
			foreach ($jobStatusList as $k => $v){
				if($v['id_status'] == 36 && $jobLastStatus[0]['id_status'] < 90){
					
					$this->view->jobId = $idJob;
					
					if($lastRecord){
						
						if($lastRecord['id_reason'] == 0 && $lastRecord['shop_code'] == $rJobDetail['shop_code'] ){
							
							$this->view->jobId = '';
						}
					}
				}
			}
		}
		
		$this->view->currentstatus = $statusRecord->getLastStatus($idJob);
			
		if($_POST){
				
			if($_POST['staff_name']==""){
	
				$this->view->resultmessage = "<span style=\"color:#FF0000;\">You Must input your Name, Record did not Save</span>";
			}
			else{
				//$statusRecord->insertStatus($idJob, $idStatus, $timeRecord, $staffRecord)
				$statusRecord->insertStatus($_POST['job_id'],$_POST['id_status'],$dateTime,$_POST['staff_name']);
				$this->view->resultmessage = "<span  style=\"color:#009900;\">Status Successfully Saved! You can Not Close this Page</span>";
			}
				
		}
			
	}	
	/**
	 * after quotation change , it should be waiting for the second invoice
	 */
	public function changequoteAction(){
		
		$idJob = $this->_getParam('jobid');
		$repairJob = new Model_DbTable_Repairjob();
		$this->view->currentprice = $repairJob->getQuotePrice($idJob);
		$secondQuote = 0;
		if($repairJob->ifFirstInvoiced($idJob)){$secondQuote = 1;}
		$this->view->idjob = $idJob;
		echo $secondQuote; 
		
		if($_POST){
						
			echo $secondQuote;
			$repairJob->updateQuotePrice($_POST['id_job'],$_POST['quote_price'],$secondQuote);
		}
		
	}
	/**
	 * This function is for input invoice in the system 
	 * the invoice can be 7 lettter after L1x or full invoice
	 * @todo possible to gather C invoice
	 */
	public function updateinvoiceAction(){

		$idJob = $this->_getParam('jobid');
		$repairJob = new Model_DbTable_Repairjob();
		$this->view->currentinvoice = $repairJob->getInvoice($idJob);
		$this->view->idjob = $idJob;
		$this->view->ifQuoteChanged = 0;
		$this->view->errorMessage = "";
		$this->view->successMessage = "";
		
		$ifQuotChanged = $repairJob->ifQuoteChange($idJob);
		
		if($ifQuotChanged){$this->view->ifQuoteChanged = 1;}
		
		if($ifQuotChanged){
			if($_POST){
				if( ( strtoupper(substr(trim($_POST['invoice_no']),0,2))=="L1" || strtoupper(substr(trim($_POST['invoice_no2']),0,2))=="L1" || strtoupper(substr(trim($_POST['invoice_no']),0,2))=="C1" || strtoupper(substr(trim($_POST['invoice_no2']),0,2))=="C1" ) && strlen(trim($_POST['invoice_no'])) == 10 ){
				
				$repairJob->updateInvoice($_POST['id_job'],$_POST['invoice_no']);
				$repairJob->updateInvoice2($_POST['id_job'],$_POST['invoice_no2']);
				$this->view->successMessage = "Invoice Added, You may now close the page";
				}
				else{
					$this->view->errorMessage = "The Invoice you input is not Full Invoice ID,Record will not Save, you need to do it again";
				}
			}			
		}
		else{
		if($_POST){
			
			if( (strtoupper(substr(trim($_POST['invoice_no']),0,2))=="L1" || strtoupper(substr(trim($_POST['invoice_no']),0,2))=="C1") && strlen(trim($_POST['invoice_no'])) == 10 ){
			
				$repairJob->updateInvoice($_POST['id_job'],$_POST['invoice_no']);
				$this->view->successMessage = "Invoice Added, You may now close the page";
			}
			else{
				$this->view->errorMessage = "The Invoice you input is not Full Invoice ID,Record will not Save, you need to do it again";
			}
			
		}
		}
	
		
		
		
	}

	/**
	 * during the job repair staff can add comment in the job 
	 */
	public function addcommentAction(){
		
		$idJob = $this->_getParam('jobid');
		$this->view->jobID = $idJob;
		$commentJob = new Model_DbTable_Jobcomments();
		
		if($_POST){
			$commentJob->addComment($_POST['id_job_repair_comt'],$_POST['staffname_repair_comt'],$_POST['content_repair_comt']);
			echo "comment ADD";
			}
		
		}
		
	/**
	 * Edit repair job status , add fix by hq status
	 * @author Leo
	 * @version 2014-09-24	
	 */	
	public function editJobStatusAction(){
		$rJob = new Model_DbTable_Repairjob();
		$stInfo = new Model_DbTable_Roster_Stafflogindetail();
		if(isset($_POST['submit'])){
			$idJob = $_POST['id_job'];
			$comment = $_POST['comment'];
			$password = $_POST['password'];
			$stLine = $stInfo->checkPasswordCorrect(Model_EncryptHelper::hashsha($password));
			if(!$stLine){
					
				echo '<script language="javascript"> window.alert("Incorrect Password, Please try your password again")</script>';
			}else{
				
				$editInfo = $stLine['ni']."(". $comment.")";
				$rJob->addFixbyHqStatus($idJob, $editInfo);
				echo "Job Id:".$idJob." has edited, you can edit another job now."."<br/>";
			}
		}
	}	
		
	/**
	 * this function will run on tuesday and friday to show out standing job alert
	 * if the job status has been change for a long time and 
	 * it alert to warehouse 
	 * @todo change my email 
	 */
	public function checkmissingmobileAction(){
		//get Today 
		//get severn days 
		//check status 
		date_default_timezone_set('Australia/Melbourne');
		
		$dateToday = Model_DatetimeHelper::dateToday();
		$date7Days = Model_DatetimeHelper::adjustDays("sub", $dateToday,6);
		
		$this->view->sendmail = $this->_getParam('email');
		$repairJobs = new Model_DbTable_Repairjob();
		$repairStatus = new Model_DbTable_Repairstatusrecord();
		
		$jobList = $repairJobs->getJobEarlyThan($date7Days);
		
		$receiver = "simon.seop@phonecollection.com.au";
		$subject = "OutStanding Repair Job Alert (More Than 7 Days)";
		$body="";
		
		$arrUnFinish = array();
		foreach($jobList as $k => $v){
			
			$statusNow = $repairStatus->getLastStatus($v['id_job']);
			if($statusNow[0]['id_status'] < 80){
				$arrUnFinish[$v['shop_code']][] = array($v['id_job'],$v['date_start'],$v['time_start']);
				
				//$body .= $v['shop_code'].' '.$v['id_job'].' '.$v['date_start'].' '.$v['time_start']."<br />";
			}
				
			
		}
		
		//d($arrUnFinish);
		$this->view->arrUnFinish = $arrUnFinish;
		$this->view->email = $receiver;
		$this->view->subject = $subject;
		$this->view->dateToday = $dateToday;
			
		}
		/**
		 * this is also check missing mobile function 
		 * it should send email to simon
		 */
	public function checkmissingmobilefridayAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		
		$dateToday = date_create(date("Y-m-d"));
		$dateToday2 =  date_create(date("Y-m-d"));	
		
		date_sub($dateToday, date_interval_create_from_date_string('4 days'));
		date_sub($dateToday2, date_interval_create_from_date_string('3 days'));	
		
		$dateBegin = date_format($dateToday, 'Y-m-d');
		$dateFirst = date_format($dateToday2, 'Y-m-d'); 

		$repairJobs = new Model_DbTable_Repairjob();
		$repairStatus = new Model_DbTable_Repairstatusrecord();

		$jobList = $repairJobs->getJobLaterThan($dateBegin);

		$receiver = "office2@phonecollection.com.au";
		$subject = "OutStanding Job Alert For Friday";
		$body="";
		
				
		foreach($jobList as $k => $v){
			
			if(strtotime($v['date_start'])== strtotime($dateFirst)){
				 if(strtotime($v['date_start']." ".$v['time_start']) > strtotime($dateFirst." 9:00:00")){
					//
					 
					 $statusNow = $repairStatus->getLastStatus($v['id_job']);
					 //print_r($statusNow);
					 if($statusNow[0]['id_status'] < 9){
						 
						  echo $v['id_job'].$v['date_start'].$v['time_start']."<br />";
						  $body .= $v['id_job'].$v['date_start'].$v['time_start']."<br />";
						 }
					 
					 }	
				 
				}
			elseif(strtotime($v['date_start'])> strtotime($dateFirst)){
				
									 $statusNow = $repairStatus->getLastStatus($v['id_job']);
					 
					 if($statusNow < 9){
						 
						  echo $v['id_job'].$v['date_start'].$v['time_start']."<br />";
						  $body .= $v['id_job'].$v['date_start'].$v['time_start']."<br />";
						 }
					 
				}	
			
			}						
				if(strlen($body)){
		
			$body = "This is a Quick Reminder That Some Out Standing Job Hasn't be DONE,Please Address it/them:<br />".$body;
		//send email
			$newMail = new Model_Emailshandler();
			$newMail->sendNormalEmail($receiver,$subject,$body);
		
		}
		
		
		
		}	
		
		/**
		 * API function for show emergency job by shop on company infopage
		 @author leo
		 */
		public function showEmergencyJobStatusAction(){
			$rjob = new Model_DbTable_Repairjob();
			$rJobStatus = new Model_DbTable_Repairstatusrecord();
			date_default_timezone_set('Australia/Melbourne');
			$dateToday = date('Y/m/d', time());
			$rJobDes = new Model_DbTable_Jobstatus();
			$sh = new Model_DbTable_Shoplocation();
			$shop = $this->_getParam("shop");
			$passwordRow = $sh->getNameByHead(trim($shop));
			$this->view->shoppassword = Model_EncryptHelper::getSslPassword($passwordRow["password_shop"]);
			$jobList = array();
			if($shop == 'COPC'){
				$emeJobList = $rjob->listAllEmergencyJobs();
				foreach($emeJobList as $k => $v){
					$lastStatus = $rJobStatus->getLastStatus($v['id_job']);
					$tmpArr = array();
					if($lastStatus[0]['id_status'] < 90 && $lastStatus[0]['id_status'] !=  80){
						$lastStatusDes = $rJobDes->getStatusDes($lastStatus[0]['id_status']);
						$tmpArr['job_id'] = $v['id_job'];
						$tmpArr['des'] = $lastStatusDes;
						$tmpArr['status'] = $lastStatus[0]['id_status'];
						$tmpArr['model'] = $v['mobile_model'];
						$tmpArr['mobile_color'] = $v['mobile_color'];
						$tmpArr['shop'] = $v['shop_code'];
						$date = Model_DatetimeHelper::dateDiff($dateToday, $v['time_record']);
						$diff = $v['level_days'] - $date;
						$tmpArr['left_days'] = $diff;
						$jobList[] = $tmpArr;
					}
				}
		
			}else{
				$emeJobList = $rjob->listShopEmergencyJobs($shop);
				foreach($emeJobList as $k => $v){
					$lastStatus = $rJobStatus->getLastStatus($v['id_job']);
					if($lastStatus[0]['id_status'] < 90 && $lastStatus[0]['id_status'] !=  80){
						$lastStatusDes = $rJobDes->getStatusDes($lastStatus[0]['id_status']);
						$tmpArr['job_id'] = $v['id_job'];
						$tmpArr['des'] = $lastStatusDes;
						$tmpArr['status'] = $lastStatus[0]['id_status'];
						$tmpArr['model'] = $v['mobile_model'];
						$tmpArr['mobile_color'] = $v['mobile_color'];
						$tmpArr['shop'] = $v['shop_code'];
						$date = Model_DatetimeHelper::dateDiff($dateToday, $v['time_record']);
						$diff = $v['level_days'] - $date;
						$tmpArr['left_days'] = $diff;
						$jobList[] = $tmpArr;
					}
				}
			}
			if(!empty($jobList)){
				$this->view->shop = $shop;
				$this->view->jobList = $jobList;
			}
		}
		
		/**
 		 * This function is for auto send remind email if emergency job not finish in 7/14/etc days 
 		 @author leo
		 */
		public function checkEmergencyJobAction(){
			
			$repairJob = new Model_DbTable_Repairjob(Zend_Registry::get('db_remoteapp'));
			$jobStatus = new Model_DbTable_Repairstatusrecord(Zend_Registry::get('db_remoteapp'));
			$allJob = $repairJob->listAllEmergencyJobs();
			date_default_timezone_set('Australia/Melbourne');
			$dateToday = date_create(date("Y-m-d"));
			$dateTest = date_format($dateToday, 'Y-m-d');
			$mail = new Model_Emailshandler();
			$mailAdd = array('office@phonecollection.com.au','simon.phonecollection@gmail.com','phonecollection.au@gmail.com');
			$receiver = array();
			$jobArray = array();
			$str = '';
			$subject = "All unfinished emergency Job Alert";
			$diff = 7;
			if($allJob!=null){
			foreach($allJob as $k => $v){
				$lastJobStatus = $jobStatus->getLastStatus($v['id_job']);
		
				foreach($lastJobStatus as $k2 => $v2){
					if($v2['id_status']== 36){
	
						$lastDateStatus = $v2['time_record'];
						$dateCheck = Model_DatetimeHelper::dateDiff($dateTest,$lastDateStatus);
						if($dateCheck == $diff || (fmod($dateCheck,$diff)) == 0 || $dateCheck == 3 || $dateCheck == 5){
							$tmpArr['job_id'] = $v['id_job'];
							$tmpArr['shop_code'] = $v['shop_code'];
							$tmpArr['repair_staff'] = $v2['staff_record'];
							$tmpArr['time_record'] = $v2['time_record'];
							$jobArray[] = $tmpArr;
		   				}
					}
				}
				
			}

			foreach($jobArray as $k3=> $v3){
				$str .= 'Job Id:'.$v3['job_id'].'<br/>'.'Shop:'.$v3['shop_code'].'<br/>'.'Staff:'.$v3['repair_staff'].'<br/>'.'Update Date:'.$v3['time_record'].'<br/>'.'<br/>';
			}
				if($jobArray!= null){
					foreach($mailAdd as $k4 => $v4){
						$mail->sendActionEmail($v4, $subject, 'All unfinished emergency job list as below,please check whether need any further '.'<br/>'.$str);
					}
				}
			}
		}
		
		/**
		 * This function is for show emergency job rank.
		 * from 2014-01-01 to today. 
		 @author leo
		 */
		public function emergencyJobRankingAction(){
			$repairJob = new Model_DbTable_Repairjob(Zend_Registry::get('db_remoteapp'));
			$jobStatus = new Model_DbTable_Repairstatusrecord(Zend_Registry::get('db_remoteapp'));
			$dateToday = Model_DatetimeHelper::dateToday();
			$startDate = '2014-01-01';
			
			$currentWeekMonday = Model_DatetimeHelper::getThisWeekMonday();
			$currentWeekSunday = Model_DatetimeHelper::getThisWeekSunday();
			$Repaircenter = unserialize(ARR_RCENTER_REV_MAPPING);
			
			$allJob = $repairJob->listAllEmergencyJobs();
			error_reporting(E_ALL ^ E_NOTICE);
			$jobRanking = array();
			$targetCycle = array(
					'0' => array('2013-12-30','2014-02-02'),
					'1' => array('2014-02-03','2014-03-02'),
					'2' => array('2014-03-03','2014-03-30'),
					'3' => array('2014-03-31','2014-04-27'),
					'4' => array('2014-04-28','2014-06-01'),
					'5' => array('2014-06-02','2014-06-29'),
					'6' => array('2014-06-30','2014-08-03'),
					'7' => array('2014-08-04','2014-08-31'),
					'8' => array('2014-09-01','2014-10-05'),
					'9' => array('2014-10-06','2014-11-02'),
					'10' => array('2014-11-03','2014-11-30'),
					'11' => array('2014-12-01','2015-01-04')
			);
			
			foreach($targetCycle as $k2 => $v2){
				if($dateToday >= $v2[0] && $dateToday <= $v2[1] ){
					$currentCycleBegin = $v2[0];
					$currentCycleEnd = $v2[1];
				}
			}
			foreach($allJob as $k => $v){
		
				if($v['shop_code'] == 'BSPC' || $v['shop_code'] == 'BSXP'){
					if($v['time_record']>= $currentWeekMonday && $v['time_record']<= $currentWeekSunday){
						$jobRanking['BSXP']['current_week'] += 1;
					}else{
						$jobRanking['BSXP']['current_week'] += 0;
					}
					
					if($v['time_record']>= $currentCycleBegin && $v['time_record']<= $currentCycleEnd){
						$jobRanking['BSXP']['current_cycle'] += 1;
					}else{
						$jobRanking['BSXP']['current_cycle'] += 0;
					}
					
					if($v['time_record']>= $startDate && $v['time_record']<= $dateToday){
						$jobRanking['BSXP']['half_year_ranking'] += 1;
					}else{
						$jobRanking['BSXP']['half_year_ranking'] += 0;
					}
					
				}
				elseif($v['shop_code'] == 'EPPC' || $v['shop_code'] == 'EPIC'){
					if($v['time_record']>= $currentWeekMonday && $v['time_record']<= $currentWeekSunday){
						$jobRanking['EPPC']['current_week'] += 1;
					}else{
						$jobRanking['EPPC']['current_week'] += 0;
					}
					
					if($v['time_record']>= $currentCycleBegin && $v['time_record']<= $currentCycleEnd){
						$jobRanking['EPPC']['current_cycle'] += 1;
					}else{
						$jobRanking['EPPC']['current_cycle'] += 0;
					}
						
					if($v['time_record']>= $startDate && $v['time_record']<= $dateToday){
						$jobRanking['EPPC']['half_year_ranking'] += 1;
					}else{
						$jobRanking['EPPC']['half_year_ranking'] += 0;
					}
				}
				elseif($v['shop_code'] == 'WBIC' || $v['shop_code'] == 'WBPC'){
					if($v['time_record']>= $currentWeekMonday && $v['time_record']<= $currentWeekSunday){
						$jobRanking['WBPC']['current_week'] += 1;
					}else{
						$jobRanking['WBPC']['current_week'] += 0;
					}
					
					if($v['time_record']>= $currentCycleBegin && $v['time_record']<= $currentCycleEnd){
						$jobRanking['WBPC']['current_cycle'] += 1;
					}else{
						$jobRanking['WBPC']['current_cycle'] += 0;
					}
						
					if($v['time_record']>= $startDate && $v['time_record']<= $dateToday){
						$jobRanking['WBPC']['half_year_ranking'] += 1;
					}else{
						$jobRanking['WBPC']['half_year_ranking'] += 0;
					}
				
				}
				elseif($v['shop_code'] == 'WGIC' || $v['shop_code'] == 'WGPC'){
					if($v['time_record']>= $currentWeekMonday && $v['time_record']<= $currentWeekSunday){
						$jobRanking['WGIC']['current_week'] += 1;
					}else{
						$jobRanking['WGIC']['current_week'] += 0;
					}
					
					if($v['time_record']>= $currentCycleBegin && $v['time_record']<= $currentCycleEnd){
						$jobRanking['WGIC']['current_cycle'] += 1;
					}else{
						$jobRanking['WGIC']['current_cycle'] += 0;
					}
						
					if($v['time_record']>= $startDate && $v['time_record']<= $dateToday){
						$jobRanking['WGIC']['half_year_ranking'] += 1;
					}else{
						$jobRanking['WGIC']['half_year_ranking'] += 0;
					}
				}
				elseif($v['shop_code'] == 'CLIC' || $v['shop_code'] == 'CLPC'){
					if($v['time_record']>= $currentWeekMonday && $v['time_record']<= $currentWeekSunday){
						$jobRanking['CLPC']['current_week'] += 1;
					}else{
						$jobRanking['CLPC']['current_week'] += 0;
					}
					
					if($v['time_record']>= $currentCycleBegin && $v['time_record']<= $currentCycleEnd){
						$jobRanking['CLPC']['current_cycle'] += 1;
					}else{
						$jobRanking['CLPC']['current_cycle'] += 0;
					}
					
					if($v['time_record']>= $startDate && $v['time_record']<= $dateToday){
						$jobRanking['CLPC']['half_year_ranking'] += 1;
					}else{
						$jobRanking['CLPC']['half_year_ranking'] += 0;
					}
				}else{
					if($v['time_record']>= $currentWeekMonday && $v['time_record']<= $currentWeekSunday){
						$jobRanking[$v['shop_code']]['current_week'] += 1;
					}else{
						$jobRanking[$v['shop_code']]['current_week'] += 0;
					}
					if($v['time_record']>= $currentCycleBegin && $v['time_record']<= $currentCycleEnd){
						$jobRanking[$v['shop_code']]['current_cycle'] += 1;
					}else{
						$jobRanking[$v['shop_code']]['current_cycle'] += 0;
					}
					
					if($v['time_record']>= $startDate && $v['time_record']<= $dateToday){
						$jobRanking[$v['shop_code']]['half_year_ranking'] += 1;
					}else{
						$jobRanking[$v['shop_code']]['half_year_ranking'] += 0;
					}
				}
			}
 			foreach($jobRanking as $k4 => $v4){
 				$restList [] = $k4;
 			}
 			if($restList != null){
				foreach($Repaircenter as $k5 => $v5){
					if(!in_array($v5,$restList)){
						$result [] = $v5;
					}
				}
				foreach ($result as $k6 => $v6){
					$jobRanking[$v6]['current_week'] = 0;
					$jobRanking[$v6]['current_cycle'] =0;
					$jobRanking[$v6]['half_year_ranking'] =0;
				}
			
				foreach($jobRanking as $k3 => $v3){
					$currentWeek[$k3] = $v3['current_week'];
					$currentcycle[$k3]  = $v3['current_cycle'];
					$toToday[$k3]  = $v3['half_year_ranking'];
				}
 			
			array_multisort($currentWeek,SORT_DESC,$currentcycle,SORT_DESC,$toToday,SORT_DESC,$jobRanking);
			
			
			
 			}
 			$this->view->shopRanking = $jobRanking;
		}
		
		/**
		 * after the job closed , you can still search the job id and find it 
		 * then you can re-open it for warranty 
		 * after warranty re-open there should be warranty by and
		 * the warranty staff should get bonus not the repair one 
		 * if repair by him self then that is ok 
		 */
		public function reOpenJobWarrantyAction(){
			
			$shopCode = $this->_getParam("shophead");
			$dateToday = Model_DatetimeHelper::dateToday();
			
			$timeNow = Model_DatetimeHelper::timeNow();
			$rJob = new Model_DbTable_Repairjob();
			$idJob = $this->_getParam("jobid");
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();
			if($_POST){

				$staffRecord = $_POST["password"];
				$comment = $_POST["comment"];
				$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($staffRecord));
				
				if(!$stLine){
					
					echo "PASSWORD incorrect, Can NOT Save , TRY AGAIN!!";
				}
				else{
					
					$rJobSt = new Model_DbTable_Repairstatusrecord();
					$rJobSt->insertStatus($idJob,7,$dateToday." ".$timeNow, $stLine['ni']);
					$rJob->updateWarrantyStaff($idJob, $stLine['id']);
					$transRecord = new Model_DbTable_Pr_Transrecord();
					$transRecord->addTransrecord($idJob, $shopCode, $stLine['id'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(),7,"Job Reopen For Warranty",-2);
					
					echo "Done,Job Has Been Re-Opened For Warranty, You may close the window now";					

					
				}
				
				
				

			}
		}
		
		/**
		 * This function is for show all refund job
		 */
		public function refundSummaryAction(){
			$rJob = new Model_DbTable_Repairjob();
			
		}
		
		/**
		 * Recording invoice of refund job.
		 */
		public function refundAction(){
			$jobId = $this->_getParam('idjob');
			$sDetail = new Model_DbTable_Roster_Stafflogindetail();
			$rJob = new Model_DbTable_Repairjob();
			$this->view->idJob = $jobId;
			if(isset($_POST['submit'])){
				$job = $rJob->getJob($jobId);
				$inv = $_POST['invoice'];
				$idstf = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST["password"])));
				if(!$idstf){
					echo '<script language="javascript"> window.alert("Incorrect Password, Please try your password again")</script>';
				}else{
					
					$rJob->updateRefund($jobId, strtoupper($inv), $idstf['id']);
					echo "Done, Refund infomation has recorded, You may close the window now";
				}
			}
		}
		
		/**
		 * after job finish ,the staff using password to record who finsih the job
		 * and job fnish 
		 */
		public function addRepairStaffAction(){
			
			$idJob = $this->_getParam("jobid");
			//$this->view->idJob =
			$sDetail = new Model_DbTable_Roster_Stafflogindetail();
			$rJob = new Model_DbTable_Repairjob();
			$jobRow = $rJob->getJob($idJob);
			$this->view->showForm = true;
			if($jobRow["repair_staff"] != 0 && $jobRow["repair_staff"] != null){
				$this->view->showForm = false;
			}
			
			if($_POST){
					
				$idStaffRow = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST["password"])));
				
				if($idStaffRow){
					$rJob->updateRepairStaff($idJob, $idStaffRow["id"]);	
					echo "Record Uploaded You may close the window Now";
				}
				else{
					echo "Password Incorrect";
				}
				
			}
			
		}
		/**
		 * show repair parts price in company info page 
		 * this page change the token every 1 hour so the staff
		 * not in the shop will not get the new token and can not see the price 
		 * if he copy the company info page , the page is locked and show nothing
		 */
		public function partsPriceAction(){
			$pv = "new"; // $this->_getParam("pv");
			
			date_default_timezone_set('Australia/Melbourne');
			
			
			$token = $this->_getParam("token");
			$this->view->error = true;
			
			if(base64_decode($token) == date("Ymdh")){
				$this->view->error = false;
			}
			
			
			if($pv == "new"){
				
				$this->renderScript('/repaircenter/parts-price-new.phtml');
			}
			
		}
		/**
		 * This is individual stock take function 
		 * this function is now combined in the weekly order 
		 * and do not use any more 
		 * 
		 */
		public function genStockTakeWeeklyAction(){
			// monday morning 
			// get last 7 days prot
			
			$arrUseList = array();
			$arrFaultyList = array();
			$arrRes = array();
			
			$shopCode = $this->_getParam("shop");
			
			$rStockMove = new Model_DbTable_Pr_Prstockmovement();
			$rProducts = new Model_DbTable_Pr_Prproducts();
			$rStock = new Model_DbTable_Pr_Prstock();
			
			$rSk = new Model_DbTable_Pr_Stocktake();
			
			$dateEnd  = Model_DatetimeHelper::dateYesterday();
			$dateBegin = Model_DatetimeHelper::adjustDays("sub", $dateEnd, 6);
			
			if($shopCode!=""){
			
			$rUseList = $rStockMove->getStockMoveSumByDateByCode(2, $dateBegin, $dateEnd, $shopCode);
			$rFautyList = $rStockMove->getStockMoveSumByDateByCode(8,$dateBegin,$dateEnd,$shopCode);
			
			foreach($rFautyList as $f){
				$arrFaultyList[]= $f["id_product"];
			}
			
			foreach($rUseList as $l){
				
				$key = false;
				$fQty = 0;
				$arrTmp = array();
				
				$arrTmp[] = $l["id_product"];
				$arrTmp[] = $l["qtys"];
				
				echo "ID:";
				echo $idProduct = $l["id_product"];
				echo "<br/>";
				if(in_array($idProduct,$arrFaultyList)){
					echo "Find";
					echo $key = array_search($idProduct,$arrFaultyList,true);	
					$arrFaultyList[$key] = " ";
					echo "<br/>";
				}
				if($key!== false){
					echo "Qty:";
				echo $fQty = $rFautyList[$key]["qtys"];
				echo "<br/>";
				}
				
				$arrTmp[] = $fQty;
				
				$arrRes[] = $arrTmp;
			}
			var_dump($arrFaultyList);
			foreach($arrFaultyList as $key => $v){
				
				if(trim($v)!==""){
					$arrTmp = array();
					$arrTmp[] = $rFautyList[$key]["id_product"];
					$arrTmp[] = 0;
					$arrTmp[] = $rFautyList[$key]["qtys"];
					
					$arrRes[] = $arrTmp;
				}
		
			}
			
			$dateTake = Model_DatetimeHelper::dateToday();
			
			foreach($arrRes as $row){
				$idProduct = $row[0];
				$pLine = $rProducts->getProduct($idProduct);
				$codeProduct = $pLine["code_product"];
				$skQty = $rStock->getShopStock($idProduct, $shopCode);
				
				$rSk->addStocktake($idProduct, $codeProduct,$shopCode, $dateTake,null,null,$row[1],$row[2],$skQty,null);
			}
			
			
			echo "<pre>";
			var_dump($arrRes);			
			echo "</pre>";
			
			echo "<pre>";
			//var_dump($rUseList,$rFautyList,$arrFaultyList);
			echo "</pre>";
			
			}
			
			
		}
		/**
		 * individual parts stock take now has been combined in to the 
		 * weekly order this function is not long in use
		 */
		public function showStockTakeWeeklyAction(){
			
			$dateToCheck = Model_DatetimeHelper::dateToday();
			$idShop = $this->_getParam("shop");
			
			$skTake = new Model_DbTable_Pr_Stocktake();
			$sList = $skTake->listByShopByDate($dateToCheck, $idShop);

			$this->view->sList = $sList;
			
			if($_POST){

				$staffName = $_POST["staff_name"];
				$time = Model_DatetimeHelper::timeNow();
				foreach($_POST["qty_act"] as $k => $v){
					
					$skTake->updateStocktakeRes($k, $staffName, $v);
				}
				
			}
			
		}

		/**
		 * this is the landing page of parts stock take and online order 
		 * In Pre stock take 
		 * it check current open job and borrowing parts 
		 * if any job without parts and any borring exist , it stops the stock take
		 * it also block staff who not familiar with the stock take 
		 * but this function is ofen misused
		 */
		public function preStockTakeAction(){
			
			$dateOrder = Model_DatetimeHelper::getThisWeekMonday();
			$this->view->orderCheck = true;
			$date2WeekBegin = Model_DatetimeHelper::adjustDays("sub",Model_DatetimeHelper::getLastWeekMonday(),7);
			$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
			$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
				
			$arrExtOrder = array();
				
			$shop = $this->_getParam("shop");
			$this->view->shop = $shop;
			$sp = $this->_getParam("sp");
			
			if($shop < 10 ){
				$idShop = "0".$shop;
			}else{
					
				$idShop = (string)$shop;
			}
			$dateOrder1 = Model_DatetimeHelper::getThisWeekMonday("");
			$partOrderNumber = "OD".$idShop.$dateOrder1;

			$rOrder = new Model_DbTable_Pr_Order();
			$rProduct = new Model_DbTable_Pr_Prproducts();
			
			$rMove = new Model_DbTable_Pr_Prstockmovement();
			$rStock = new Model_DbTable_Pr_Prstock();
			$rJob = new Model_DbTable_Repairjob();
			$rsRecord = new Model_DbTable_Repairstatusrecord();
			$stInfo = new Model_DbTable_Roster_Stafflogindetail();
			
			$rOrderCheck = $rOrder->getByPON($partOrderNumber);
			$count = 0;
			if($rOrderCheck){
				foreach ($rOrderCheck as $key => $oDetail){
					if(!empty($oDetail['qty_order_actual'])){
						$count ++;
					}
				}
			
				if($count>0){
					$this->view->orderCheck = false;
				}
			}
			if($sp == 'yes'){
				$this->view->orderCheck = true;
			}
			
$arrShopList = self::$rCenterMappingReserve[$shop];
			
			$resultPass = true;
			$errorMessage = "";
			
			foreach($arrShopList as $shopHead){
				//echo $shopHead;
				
				$jList = $rJob->listUnfinishedJobByShop($shopHead);
				
				foreach($jList as $k => $rJobRow){
					
					//echo $rJobRow['id_job'];
					$recordRow = $rsRecord->getLastStatus($rJobRow['id_job']);
					
					
					if((int)$recordRow[0]['id_status'] == 10){
					
						$resultPass = true;
					}
					else{
						
						if((int)$recordRow[0]['id_status'] < 80){
							
							$partsLine = $rMove->getPartsRecordByJobId($rJobRow['id_job']);
							if(empty($partsLine)) {
							
							$resultPass = false;
							//echo "ERROR 1";
							$errorMessage .="Parts Record Missing ({$rJobRow['id_job']}) <br />";
							}
							
						}
					}
					
					// get parts 
					
	
				}
				
			}
			
			$rBorrow = new Model_DbTable_Pr_Loan();
			$borrowList = $rBorrow->unconfirmedExistList($shop);
			if($borrowList){
				
				$resultPass = false;
				//echo "ERROR 2";
				foreach($borrowList as $kb => $vb){
				
					$errorMessage .="Borrorw Not Confirmed {$vb['id_job']} - [<a href='http://".WEB_IP."/repairparts/confirm-borrow/bcode/{$vb['b_code']}' target = '_blank' >{$vb['b_code']}</a>] <br />";
				}
			}
			
			$this->view->resultPass = $resultPass;
			$this->view->errorMessage = $errorMessage;
			

			
			
			if($_POST){
				
				$stLine = $stInfo->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['pwd']));
				
				if(!$stLine){
					
					echo '<script language="javascript"> window.alert("Incorrect Password, Please try your password again")</script>';
				}
				else{
					if(isset($_POST['btn_not_ok'])){
						$this->view->notPass = true;
						$stInfo->noScanParts($stLine['id']);
						
						$mail = new Model_Emailshandler();
						$mail->sendNormalEmail("eco3@phonecollection.com.au", "I am not familiar", $stLine['id']);
					}
					
					if(isset($_POST['btn_begin'])){
						
						if($stLine['scan_parts']==2){
							$this->view->notPass = true;
						}else{
							$this->view->notPass = false;
							if(isset($_POST['regern_stock'])){
							
							$this->_redirect("/repairparts/last-week-parts-sales/shop/".$shop."/staff/".$stLine['id']);
							}
							else{
								$this->_redirect("/repaircenter/online-order/shop/".$shop);
							}
						}	
					}
						
				}
				
			}
			
			
		}
		
		public function stockTakeHistoryAction(){
			$dateOrder1 = Model_DatetimeHelper::getThisWeekMonday("");
			$dateOrderLast = Model_DatetimeHelper::adjustDays(sub, $dateOrder1, 7,"");
			$shop = $this->_getParam("shop");
			if($shop < 10 ){
				$idShop = "0".$shop;
			}else{
					
				$idShop = (string)$shop;
			}
			$partOrderNumber = "OD".$idShop.$dateOrder1;
			$partOrderNumber2 = "OD".$idShop.$dateOrderLast;
			
			$rOrder = new Model_DbTable_Pr_Order();

				
			$rOrderCheck = $rOrder->getByPON($partOrderNumber);
			$rOrderCheck2 = $rOrder->getByPON($partOrderNumber2);
			$this->view->orderDate1 = $dateOrder1;
			$this->view->orderDate2 = $dateOrderLast;
			$this->view->oList = $rOrderCheck;
			$this->view->oList2 = $rOrderCheck2;
		}
		
		/**
		 * This is for WH stock take
		 */
		public function whStockTakeAction(){
			$prStock = new Model_DbTable_Pr_Prstock();
			$prProduct = new Model_DbTable_Pr_Prproducts();
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();
			$rMove = new Model_DbTable_Pr_Prstockmovement();
			$rOrder = new Model_DbTable_Pr_Order();
			$shop = $this->_getParam('shop');
			$part = $this->_getParam('part');
			
			
			
			$prList = array();
			$arrPart = array();
			$this->view->arrParts = $arrPart;
			if($shop == 'WHPC'){
				$tmpList = $prProduct->listAllActive();
				
				foreach ($tmpList as $k => $v){
					$whstock = $prStock->getWarehouseStock($v['id_product']);
					$unactQty = $rOrder->qtyOnOrder($v['code_product']);
					
					if(!empty($v['is_lcd'])){
						$prList['SCREEN'][$v['id_product']]['info'] = $v;
						$prList['SCREEN'][$v['id_product']]['stock'] = $whstock;
						$prList['SCREEN'][$v['id_product']]['qty_unactive'] = $unactQty;
						
					}else{
						$prList['PARTS'][$v['id_product']]['info'] = $v;
						$prList['PARTS'][$v['id_product']]['stock'] = $whstock;
			
						$prList['PARTS'][$v['id_product']]['qty_unactive'] = $unactQty;

					}
					
				}

				if(isset($_POST['checkdiff'])){
					$list = $_POST['qty_onhand_cf'];
					foreach ($list as $idProduct => $qty){
						$arrPart[$idProduct] = $qty;
					}
				}
				
				if(isset($_POST['btn_confirm_stocktake'])){
					$dateTody = Model_DatetimeHelper::dateToday("");
					$timeNow = Model_DatetimeHelper::timeNow("");
					$aINo = "AD".$dateTody.$timeNow;
					$pwd = $_POST['pwd'];
					$list = $_POST['qty_onhand_cf'];
					foreach ($list as $idProduct => $qty){
						$arrPart[$idProduct] = $qty;
					}
					
					$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($pwd));
					if($stLine){
						foreach($_POST['qty_onhand_cf'] as $key => $v){
							if($v != 0){
							$prStock->updateStockWarehouse($key, $v);
							$diff = $_POST['qty_diff'];
							
							if($diff[$key] != 0){
								if($diff[$key] >0){
					
									$rMove->addMovement(5, $key, $diff[$key],$stLine['ni'],0,$aINo);
								}
								else{
									$rMove->addMovement(6, $key, 0 - $diff[$key],$stLine['ni'],0,$aINo);
								}
								
								$tmpStock = $prStock->getWarehouseStock($key);
								$rMove->addMovement(9, $key, $tmpStock,$stLine['ni'],0,$aINo);
							}
							}
						}			
						
						$this->view->finish = true;
					}else{
						
						echo '<script language = "javascript" >alert("Incorrect Password!! Type Password And Submit Again");</script>';
					}
					
				}
				
				$this->view->arrParts = $arrPart;
				$this->view->list = $prList;
				$this->view->check = $part;
			}
		}
		
		/**
		 * this is the online order fucntion 
		 * online order contains two page 
		 * 1. stock take 
		 * 2. order 
		 * stock take page is separated into 2 section 
		 * LCD / non-LCD
		 * lcd one is must scan , non lcd one you can put the numbers in 
		 * @todo for non lcd one , you should not put -1 number , now it is still ok 
		 * 
		 * After the stock take , the stff now can do the order 
		 * they can modify the order Qty and add barcode they want 
		 * after that ,  they send the notice to warehouse and warehouse pickup the order
		 * @todo if order has been modified , sending email notice.even it is not submited 
		 * 
		 *                         
		 */
		public function onlineOrderAction(){
		
			$dateOrder = Model_DatetimeHelper::getThisWeekMonday();
			//get tuesday
			$dateOrderTuesday = $dateOrder+1;
			// WGshops 
			
			$date2WeekBegin = Model_DatetimeHelper::adjustDays("sub",Model_DatetimeHelper::getLastWeekMonday(),7);
			$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
			$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
			
			$arrExtOrder = array();
			
			$shop = $this->_getParam("shop");
		
			$rOrder = new Model_DbTable_Pr_Order();
			$rProduct = new Model_DbTable_Pr_Prproducts();
			$rMove = new Model_DbTable_Pr_Prstockmovement();
			$rStock = new Model_DbTable_Pr_Prstock();
			$rJob = new Model_DbTable_Repairjob();
			$rsRecord = new Model_DbTable_Repairstatusrecord();
			$stInfo = new Model_DbTable_Roster_Stafflogindetail();
			
			$arrShopList = self::$rCenterMappingReserve[$shop];
			
			$resultPass = true;
			$errorMessage = "";
			/*
			foreach($arrShopList as $shopHead){
				//echo $shopHead;
				
				$jList = $rJob->listUnfinishedJobByShop($shopHead);
				
				foreach($jList as $k => $rJobRow){
					
					//echo $rJobRow['id_job'];
					$recordRow = $rsRecord->getLastStatus($rJobRow['id_job']);
					
					
					if((int)$recordRow[0]['id_status'] == 10){
					
						$resultPass = true;
					}
					else{
						
						if((int)$recordRow[0]['id_status'] < 80){
							
							$partsLine = $rMove->getPartsRecordByJobId($rJobRow['id_job']);
							if(empty($partsLine)) {
							
							$resultPass = false;
							//echo "ERROR 1";
							$errorMessage .="Parts Record Missing ({$rJobRow['id_job']}) |";
							}
							
						}
					}
					
					// get parts 
					
	
				}
				
			}
			*/

			$rBorrow = new Model_DbTable_Pr_Loan();
			//$borrowList = $rBorrow->unconfirmedExistList($shop);
			/*
			if($borrowList){
				
				$resultPass = false;
				//echo "ERROR 2";
				foreach($borrowList as $kb => $vb){
				
					$errorMessage .="Borrorw Not Confirmed {$vb['id_job']} - [<a href='http://".WEB_IP."/repairparts/confirm-borrow/bcode/{$vb['b_code']}' target = '_blank' >{$vb['b_code']}</a>] |";
				}
			}
			*/
			if(trim($errorMessage)!=""){
			
				$this->_redirect("/repaircenter/pre-stock-take/shop/".$shop);
			}
			
			$this->view->resultPass = $resultPass;
			$this->view->errorMessage = $errorMessage;
			
			$arrPart = array();
			
			if($_POST){
				
				
				if($_POST['part_code']!=""){
					$this->view->hiddenpart = $_POST['part_code'];
				}
				if(isset($_POST['str_part'])){
				$arrPart = unserialize(gzuncompress(base64_decode($_POST['str_part'])));
				}
				// stock take page
				//submit
				
				if(isset($_POST['btn_submit'])){
					//d($_POST['part_code']);
					foreach($_POST['qty_onhand_cf'] as $idOrder => $qtyCf){
						$partLine = $rOrder->getOrder($idOrder) ;
						$partCodeLine = $partLine['code_product'];
					
						if(isset($arrPart[$partCodeLine])){
							
							$arrPart[$partCodeLine] = $qtyCf;
						}
					
					}					
					if(isset($_POST['part_code']) && $_POST['part_qty'] != 0){
						$arrPart[$_POST['part_code']] += $_POST['part_qty'];
					
					}else if($_POST['part_code']){
						$arrPart[$_POST['part_code']] += 1;
					
					}
					else{
						$arrPart[$_POST['part_code']] = 1;
						
					}
						
				}
				//cancel
				if(isset($_POST['btn_cancel'])){
					
					foreach($_POST['qty_onhand_cf'] as $idOrder => $qtyCf){
						$partLine = $rOrder->getOrder($idOrder) ;
						$partCodeLine = $partLine['code_product'];
							
						if(isset($arrPart[$partCodeLine])){
								
							$arrPart[$partCodeLine] = $qtyCf;
						}
							
					}
					
				
					if($_POST['hidden_part']!=""){
						
						$arrPart[$_POST['hidden_part']] -= 1;
					}
					
					$this->view->hiddenpart = "";
					
				}
				//confirm
				if(isset($_POST['btn_confirm_stocktake'])){
					
					//updat Qty
					//check password 
					
					$stLine = $stInfo->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['pwd']));
					if($stLine){
						
						foreach($_POST['qty_onhand_cf'] as $key => $v){
							$rOrder->updateStockTake($key, $v,$stLine['id'],$_POST['comment']);
							//$rOrder->updateStockTake($key+1, $v,$stLine['id'],$_POST['comment']);
						}			
					}else{
						
						echo '<script language = "javascript" >alert("Incorrect Password!! Type Password And Submit Again");</script>';
						$this->view->arrWrongpass = $_POST['qty_onhand_cf'];
					}					
					$str = Model_System_Downloadhelper::downloadUrl("http://".WEB_IP."/repairparts/parts-stock-take-summary-shop/email/yes/shop/".$shop);
					
				}
				// input order page 
				
				if(isset($_POST['btn_save_st'])){
					$res = $stInfo->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST['staff_name_stocktake'])));
					if($res!==false){
					
					foreach($_POST['qty_onhand_cf'] as $k => $v){

						if(is_numeric($v)){
						$rOrder->updateStockTake($k,$v, $res['id']);
						}
					}
					
					}
					else{
						echo "<h2> Incorrect Password </h2>";
					}
					
				}
				
				//Add barcode
				if(isset($_POST["arr_ext_order"])){
				$arrExtOrder = unserialize(base64_decode($_POST["arr_ext_order"]));
				}
				
				if(isset($_POST["btn_add"])){
					$idAddPro = $_POST["add_part_code"];
					if($idAddPro!=""){	
					$proRow = $rProduct->find($idAddPro);
					$codePro = $proRow[0]["code_product"];
					$desPro = $proRow[0]["title_product"];
					
					$rListGo = $rMove->getProductMoveSummaryByDateByCode(2,$idAddPro,$date2WeekBegin, $dateEnd,$shop);
					$rListFo = $rMove->getProductMoveSummaryByDateByCode(8,$idAddPro,$dateBegin, $dateEnd,$shop);
					$rListEi = $rMove->getProductMoveSummaryByDateByCode(7,$idAddPro,$dateBegin, $dateEnd,$shop);
					
					$qtyLastWeek = round($rListGo[0]['sum_qty']/2,0);
					$maxSold = $rMove->maxSold($idAddPro, $dateEnd,4,$shop);
					$qtyFaulty = $rListFo[0]['sum_qty'] - $rListEi[0]['sum_qty'];
					
					$qtyOnhand = $rStock->getShopStock($idAddPro, $shop);
					$qtyWh = $rStock->getWarehouseStock($idAddPro);
					
					$qtyOrder = $rOrder->orderQty($qtyLastWeek, $maxSold, $qtyFaulty, $qtyOnhand, $qtyWh);
					$arrExtOrder[$idAddPro] = array($idAddPro,$codePro,$desPro,$qtyLastWeek,$maxSold,$qtyFaulty,$qtyOnhand,$qtyWh,$qtyOrder,"");
					}
				}
				// save the list 
				if(isset($_POST["btn_save"]) || isset($_POST["btn_confirm"])){
					//var_dump($_POST["qty_order"]);
					//update the Order Qty
					foreach($_POST["qty_order"] as $ko => $vo){
					$rOrder->updateOrderQty($ko, $vo,$_POST["reason"][$ko]);	
					//$rOrder->updateBackOrderQty($ko, $_POST["qty_backorder"][$ko]);
					}
					//Insert New Row
					foreach($arrExtOrder as $ke => $ve){	
						//$rOrder->addOrder($partOrderNumber, $idShop, $dateOrder, $idProduct, $codeProduct, $qtyLastWeek, $qtyFoLastWeek, $qtyMaxWeek, $qtyOnhand, $qtyWh);
						if($_POST["qty_onhand_cf_ext"][$ke]!=""){
						$idRow = $rOrder->addOrder($_POST["part_order_number"], $shop, $dateOrder, $ve[0], $ve[1], $ve[3], $ve[5], $ve[4], $ve[6], $ve[7],$_POST["qty_ext_order"][$ke]);
						$rOrder->updateOrderQty($idRow,$_POST["qty_ext_order"][$ke], null);
						$rOrder->updateStockTake($idRow,$_POST["qty_onhand_cf_ext"][$ke], null);
						}
						else{
							
							echo '  <script>
  alert("Actual On-hand Qty For Your Extra Parts Order Is Missing, The Extra Order Can Not Be Add In!!");
  </script>';
						}
					}
					
					$arrExtOrder = array();
				}
				//send 
				if(isset($_POST["btn_confirm"])){
					
					$res = $stInfo->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST['staff_name'])));
					
					if($res!==false){
					$rOrder->confirmOrder($_POST["part_order_number"]);
							
					$rOrder->updateStaffName($_POST["part_order_number"],$res['id']);		
					
					$mail = new Model_Emailshandler();
					$receiver = "office@phonecollection.com.au";
					$subject = "Parts Order:{$_POST["part_order_number"]} has been confirmed have a look";
					$mailbody = "Check it in the Control Panel Or copy the link here: http://".WEB_IP."/repairparts/pickup-slip-order/pon/{$_POST["part_order_number"]}";
					$mail->sendActionEmail($receiver, $subject, $mailbody);					
					}else{

						echo "<h2> Incorrect Password </h2>";
						
					}
				}
				//del item 
				if(isset($_POST["btn_del"])){
				
					foreach($_POST['id_remove'] as $k => $v){
						unset($arrExtOrder[$k]);
					}
				}				
				
			}
			
			$this->view->strPart = base64_encode(gzcompress(serialize($arrPart)));
			$this->view->arrParts = $arrPart;
			$this->view->arrExtOrder = base64_encode(serialize($arrExtOrder));
			$this->view->pList = $pList = $rProduct->listAllProducts();
			
			$oList = $rOrder->getOrderByShopByDate($shop, $dateOrder);
			$this->view->oList = $oList;
			$this->view->idShop = $shop;
			
			$onHandConfirm = $oList[0]['qty_onhand_cf'];
			$orderDone = $rOrder->stockTakeDone($shop, $dateOrder);
			
			$this->view->mustScanShop = true;
			
			if($shop == 9){
				
				$this->view->mustScanShop = false;
			}
			
			if(!$orderDone[0]){
				$this->renderScript( 'repaircenter/online-order-stocktake-scan.phtml' );	
			}
			else{
				
				$this->renderScript( 'repaircenter/online-order.phtml' );
			}
			//var_dump($oList);
		}
		/**
		 * For Tuesday NON-LCD parts stock take 
		 * @todo Check if the parts stock take is been done or not 
		 * this function is made by leo 
		 * For parts stock take
		 * @version 2014-08-06
		 * @author Leo
		 */
		public function prePartsStockTakeAction(){
			$dateOrder = Model_DatetimeHelper::getThisWeekMonday();
			$dateTuesday = Model_DatetimeHelper::adjustDays('add', $dateOrder, 1);
			$dateOrderMonday = Model_DatetimeHelper::getThisWeekMonday("");
			$dateOrderTuesday = $dateOrderMonday+1;
			$date2WeekBegin = Model_DatetimeHelper::adjustDays("sub",Model_DatetimeHelper::getLastWeekMonday(),7);
			$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
			$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
			
			$arrExtOrder = array();
			$shop = $this->_getParam("shop");
			if($shop < 10 ){
				$idShop = "0".$shop;
			}else{
				$idShop = (string)$shop;
			}
			
			
			$fakeOrderNumber = "OD".$idShop.$dateOrderTuesday;
			$rOrder = new Model_DbTable_Pr_Order();
			$rProduct = new Model_DbTable_Pr_Prproducts();
			$rMove = new Model_DbTable_Pr_Prstockmovement();
			$rStock = new Model_DbTable_Pr_Prstock();
			$rJob = new Model_DbTable_Repairjob();
			$rsRecord = new Model_DbTable_Repairstatusrecord();
			$stInfo = new Model_DbTable_Roster_Stafflogindetail();
				
				
			$arrShopList = self::$rCenterMappingReserve[$shop];
				
			$resultPass = true;
			$errorMessage = "";
				
			foreach($arrShopList as $shopHead){
				//echo $shopHead;
			
				$jList = $rJob->listUnfinishedJobByShop($shopHead);
			
				foreach($jList as $k => $rJobRow){
						
					//echo $rJobRow['id_job'];
					$recordRow = $rsRecord->getLastStatus($rJobRow['id_job']);
						
						
					if((int)$recordRow[0]['id_status'] == 10){
							
						$resultPass = true;
					}
					else{
			
						if((int)$recordRow[0]['id_status'] < 80){
								
							$partsLine = $rMove->getPartsRecordByJobId($rJobRow['id_job']);
							if(empty($partsLine)) {
									
								$resultPass = false;
								//echo "ERROR 1";
								$errorMessage .="Parts Record Missing ({$rJobRow['id_job']}) <br />";
							}
								
						}
					}

				}
			
			}
				
			$rBorrow = new Model_DbTable_Pr_Loan();
			$borrowList = $rBorrow->unconfirmedExistList($shop);
			if($borrowList){
			
				$resultPass = false;
				//echo "ERROR 2";
				foreach($borrowList as $kb => $vb){
			
					$errorMessage .="Borrorw Not Confirmed {$vb['id_job']} - [<a href='http://".SERVER_IP_PUBIC.":1080/repairparts/confirm-borrow/bcode/{$vb['b_code']}' target = '_blank' >{$vb['b_code']}</a>] <br />";
				}
			}
				
			$this->view->resultPass = $resultPass;
			$this->view->errorMessage = $errorMessage;
			
			if($_POST){
			
				$stLine = $stInfo->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['pwd']));
			
				if(!$stLine){
						
					echo '<script language="javascript"> window.alert("Incorrect Password, Please try your password again")</script>';
				}
				else{
					if(isset($_POST['btn_not_ok'])){
						$this->view->notPass = true;
						$stInfo->noScanParts($stLine['id']);
			
						$mail = new Model_Emailshandler();
						$mail->sendNormalEmail("eco3@phonecollection.com.au", "I am not familiar", $stLine['id']);
					}
						
					if(isset($_POST['btn_begin'])){
			
						if($stLine['scan_parts']==2){
							$this->view->notPass = true;
						}else{
							$this->view->notPass = false;
							if(isset($_POST['regern_stock'])){
								$rOrder->clearOrder($dateTuesday, $shop);
								$partsList = array();	
								$arrList = array();
								$allPartsList = $rProduct->listAllNoneLcd();
								$rListTi = $rMove->getStockMoveSumByDateByCode(3, $dateBegin, $dateEnd,$shop);
								foreach($allPartsList as $key => $val){
									$tmpArray = array();
									$partStock = $rStock->getShopStock($val['id_product'], $shop);
									if($partStock > 0){
									 	$tmpArray['id_product'] = $val['id_product'];
									 	$tmpArray['code_product'] = $val['code_product'];
									 	$tmpArray['stock'] = $partStock;
									 	$arrList[] = $val['id_product'];
									 	$partsList[] = $tmpArray;
									}
								}
								if(!empty($rListTi)){
									foreach($rListTi as $k2 => $v2){
										$partsDetail = $rProduct->getProduct($v2['id_product']);
										if($partsDetail['is_lcd'] != 1){
											$tmpArray = array();
											$key = array_search($v2['id_product'], $arrList);
											if($key === false){
												$tmpArray['id_product'] = $v2['id_product'];
												$codeProduct = $rProduct->getProduct($v2['id_product']);
												$tmpArray['code_product'] = $codeProduct['code_product'];
												$qtyOnhand = $rStock->getShopStock($v2['id_product'], $shop);
												$tmpArray['stock'] = $qtyOnhand;
												$partsList[] = $tmpArray;
												$arrList[] = $v2['id_product'];
											}
										}
									}
								}

								foreach($partsList as $k3 => $v3){
									
									$rOrder->addOrder($fakeOrderNumber, $shop, $dateTuesday, $v3['id_product'], $v3['code_product'], 0, 0, 0, $v3['stock'], 0,0);
								
								}

								$this->_redirect("/repaircenter/parts-stock-take/shop/".$shop);
							}
							else{
								$this->_redirect("/repaircenter/parts-stock-take/shop/".$shop);
							}
						}
					}
			
				}
			
			}
			
		}
		
		/**
		 * the actual page of parts (NON-LCD) stock take page
		 * this only happen on tuesday
		 */
		
		public function partsStockTakeAction(){
			
			$dateOrder = Model_DatetimeHelper::getThisWeekMonday();
			$dateToday = Model_DatetimeHelper::dateToday();
			if($dateToday == $dateOrder){
				
				$this->view->message = "You cannot do parts stock take on Monday";
				$this->renderScript( 'repaircenter/fake-online-order.phtml' );
				return false;
			}
			
			//get tuesday
			$dateOrderTuesday = Model_DatetimeHelper::adjustDays("add", $dateOrder, 1);
			
			$date2WeekBegin = Model_DatetimeHelper::adjustDays("sub",Model_DatetimeHelper::getLastWeekMonday(),7);
			$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
			$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
				
			$arrExtOrder = array();
				
			$shop = $this->_getParam("shop");
			
			$rOrder = new Model_DbTable_Pr_Order();
			$rProduct = new Model_DbTable_Pr_Prproducts();
			$rMove = new Model_DbTable_Pr_Prstockmovement();
			$rStock = new Model_DbTable_Pr_Prstock();
			$rJob = new Model_DbTable_Repairjob();
			$rsRecord = new Model_DbTable_Repairstatusrecord();
			$stInfo = new Model_DbTable_Roster_Stafflogindetail();
				
			$arrShopList = self::$rCenterMappingReserve[$shop];
				
			$resultPass = true;
			$errorMessage = "";
			$arrPart = array();
			$oList = $rOrder->getOrderByShopByDate($shop, $dateOrderTuesday);
			foreach($oList as $k2 => $v2){
				$orderNo = $v2['part_order_number'];
			}

			//d($olist);
			
			//d($orderDone);
			
			
			if($_POST){
				
				//d($_POST['hidden_part']);
			
				if($_POST['part_code']!=""){
					$this->view->hiddenpart = $_POST['part_code'];
				}
				if(isset($_POST['str_part'])){
					$arrPart = unserialize(gzuncompress(base64_decode($_POST['str_part'])));
				}
				// stock take page
				//submit
			
				if(isset($_POST['btn_submit'])){
					foreach($_POST['qty_onhand_cf'] as $idOrder => $qtyCf){
						$partLine = $rOrder->getOrder($idOrder) ;
						$partCodeLine = $partLine['code_product'];
							
						if(isset($arrPart[$partCodeLine])){
								
							$arrPart[$partCodeLine] = $qtyCf;
						}
							
					}
					if(isset($_POST['part_code']) && $_POST['part_qty'] != 0){
						$arrPart[$_POST['part_code']] += $_POST['part_qty'];
							
					}else if($_POST['part_code']){
						$arrPart[$_POST['part_code']] += 1;
							
					}
					else{
						$arrPart[$_POST['part_code']] = 1;
					
					}
			
				}
				//cancel
				if(isset($_POST['btn_cancel'])){
						
					foreach($_POST['qty_onhand_cf'] as $idOrder => $qtyCf){
						$partLine = $rOrder->getOrder($idOrder) ;
						$partCodeLine = $partLine['code_product'];
							
						if(isset($arrPart[$partCodeLine])){
			
							$arrPart[$partCodeLine] = $qtyCf;
						}
							
					}
						
			
					if($_POST['hidden_part']!=""){
			
						$arrPart[$_POST['hidden_part']] -= 1;
					}
						
					$this->view->hiddenpart = "";
						
				}
			
			
			if(isset($_POST['btn_confirm_stocktake'])){

				$stLine = $stInfo->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['pwd']));
				if($stLine){
			
					foreach($_POST['qty_onhand_cf'] as $key => $v){
						$rOrder->updateStockTake($key, $v,$stLine['id'],$_POST['comment']);
					}
				}else{
			
					echo '<script language = "javascript" >alert("Incorrect Password!! Type Password And Submit Again");</script>';
					$this->view->arrWrongpass = $_POST['qty_onhand_cf'];
				}
				$str = Model_System_Downloadhelper::downloadUrl("http://".WEB_IP."/repairparts/parts-stock-take-summary-shop/email/yes/shop/".$shop);
			}
		}
				
		$this->view->strPart = base64_encode(gzcompress(serialize($arrPart)));
		$this->view->arrParts = $arrPart;
		$this->view->arrExtOrder = base64_encode(serialize($arrExtOrder));
		$this->view->pList = $pList = $rProduct->listAllProducts();
		
		$this->view->oList = $oList;
		$this->view->idShop = $shop;
		
		$onHandConfirm = $oList[0]['qty_onhand_cf'];
		$orderDone = $rOrder->stockTakeDone($shop, $dateOrderTuesday);
		
		$this->view->mustScanShop = true;
			
		if($shop == 9){
				
			$this->view->mustScanShop = false;
		}
			
		if(!$orderDone[0]){
			$this->renderScript( 'repaircenter/parts-stock-take.phtml' );
		}
		else{
			$this->view->message = "Your parts stock take has finished, you can close the window";
			$this->renderScript( 'repaircenter/fake-online-order.phtml' );
		}
			
			
		
			
			
		}
		
		/**
		 * this is the function left staff check if the order received is correct
		 * this page has been updated so the staff must scan to confirm the 
		 * qty of the parts
		 * 
		 */
		
		public function orderConfirmAction(){
			
			$pon = $this->_getParam("pon");
			$this->view->orderNo = $pon;
			
			$rOrder = new Model_DbTable_Pr_Order();
			$rProduct = new Model_DbTable_Pr_Prproducts();
			$rMove = new Model_DbTable_Pr_Prstockmovement();
			$rStock = new Model_DbTable_Pr_Prstock();
			$rOrderAsKt = new Model_DbTable_Products_Stock_Transferadjuststatus();
			$kaktRecord = new Model_DbTable_Products_Stock_Kaktstatusrecord();
			
			
			
			$oList = $rOrder->getByPON($pon);
			
			$arrParts = array();
			if($_POST){
				$arrParts = unserialize(gzuncompress(base64_decode($_POST['str_part'])));
				
				//echo "<pre>";
				//var_dump($arrParts);
				//echo "</pre>";
				
				// if cancel 
				if(isset($_POST['btn_cancel'])){
					if($_POST['hidden_part'] !="K35BCKECOCE"){
					
					$arrParts[$_POST['hidden_part']] = $arrParts[$_POST['hidden_part']] -1;

					$this->view->hiddenpart = "K35BCKECOCE";
					}
				}
				//else
				else{
					$this->view->hiddenpart = $_POST['part_code'];
					
					if(isset($arrParts[$_POST['part_code']])){
						$arrParts[$_POST['part_code']] = $arrParts[$_POST['part_code']] + 1;
					}
					else{
						
						$arrParts[$_POST['part_code']] = 1;	
					}	
				}
				
				
				 	
			}
			$this->view->strPart = base64_encode(gzcompress(serialize($arrParts)));
			
			$this->view->arrParts = $arrParts;
			
			/*
			 * Do Not Update Stock Now 
			 * 
			if($_POST){
				foreach($oList as $key => $v){
					// change stock , add movement
					//warehouse stock -
					$rStock->descreaseStockWarehouse($v["id_product"], $v["qty_allocate"]);
					//shop stock +
					$rStock->increaseStockShop($v["id_product"], $v["qty_allocate"],$v["id_shop"]);
					//record movement
					$rMove->addMovement(3,$v["id_product"], $v["qty_allocate"],"repair Parts Order",$v['id_shop'],trim($pon));

					
				}
					
				$idKa = $rOrderAsKt->getStatusByNumber(trim($pon));
				$rOrderAsKt->activeTheTransfer($idKa["id"],Model_DatetimeHelper::dateToday(),'Phone Repair');
				$kaktRecord->addRecord($idKa["id"],99,"repair part");
				$rOrder->OrderSent(trim($pon));
			
				echo "You Confirmed The Order Sent In Correct Qty, You may Close the Window Now";	
				//active kakt			
			}
			*/
			
			
			$this->view->oList = $rOrder->getByPON($pon);
			
			
			$this->renderScript( 'repaircenter/order-confirm-scan.phtml' );
			
		}
		/**
		 * this is the actual submition page of order confirm scan 
		 * after scan and find out the difference 
		 * the difference and staff comment using this page to submit 
		 */
		
		public function orderConfirmReportAction(){
			
			//var_dump($_POST);
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();
			
			$knote = new Model_DbTable_Products_Stock_Transferadjuststatus();
			$krecord = new Model_DbTable_Products_Stock_Kaktstatusrecord();
			
			$row = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['pwd']));
			if($row){
				//password check pass
				$idNote = $knote->getStatusByNumber(trim($_POST['order_no']));
				
				if(trim($_POST['difference'])==""){
					$statusCode = 2;
					
					//nothing wrong 
					$knote->updateStatus($idNote['id'], $statusCode);
					$krecord->addRecord($idNote['id'], $statusCode, $row['ni'],nl2br($_POST['comment']));
					echo "You record has been Updated in the System , Warehouse will Find the Error For you, you may close the window now";
				}
				else{
					$statusCode = 4;
					//met errors
					$knote->updateStatus($idNote['id'], $statusCode);
					$krecord->addRecord($idNote['id'], $statusCode,$row['ni'],nl2br($_POST['difference'].$_POST['comment']));
					
					echo "You record has been Updated in the System , Warehouse will Active the Order For you, you may close the window now";
				}
				
				
			}
			else{
				
				echo "Password Check Fail, Please go back and Submit again";
			}
		}
		
		/**
		 * this is the function to update update on screen IMEI 
		 * if no on screen IMEI the job can not close 
		 */
		public function updateImeiAction(){
			$idJob = $this->_getParam("idjob");
			$repJob = new Model_DbTable_Repairjob();
						
			if($_POST){
					
			$repJob->updateOnScreenImei($idJob, trim($_POST['on_screen_imei']));	
				
			}
			
			$jobRow = $repJob->getJob($idJob);
			
			$this->view->deviceImei = $jobRow['mobile_imei'];
			$this->view->onscreenImei = $jobRow['on_screen_imei']; 
			$this->view->noImeiReason =  $jobRow['no_imei_reason'];
			
		}
		
		/**
		 * API function for check quick form information fill in 
		 */
		public function quickFormAction(){
			
			$this->view->shopCode = $this->_getParam("shop");
			
			$error = $this->_getParam("error");
			
			if($error == "yes"){

				$this->view->error = "You must FILL IN ALL the fields in Quick Form,Please Do it Again!!";
				
			}
			
			
			
		}
		/**
		 * Api function for save quick form job
		 @author leo
		 */
		public function quickFormConfirmquoteAction(){
			
			//d($_POST);
			
			date_default_timezone_set('Australia/Melbourne');
			$jobIdDate = intval(date("Ymd"));
			$jobIdCounter = new Model_DbTable_Jobidcounter();
				
			$repairJob = new Model_DbTable_Repairjob();
			$statusRecord = new Model_DbTable_Repairstatusrecord();
			$newCounter = $jobIdCounter->runCounter();
			$transRecord = new Model_DbTable_Pr_Transrecord();
			

			$newJobID = "";
			
			//must fill in all
			if( !isset($_POST['repair_type']) || !isset($_POST['staff_name']) || !isset($_POST['cust_phone']) || !isset($_POST['cust_name']) || !is_numeric($_POST['mobile_imei'])){

				$this->_redirect("/repaircenter/quick-form/shop/".$_POST['shop_code']."/error/yes");
			}else{

				$newJobID = $jobIdDate*100000 + $newCounter;
			
				$this->view->newjobid = $newJobID;

				$dateToday = Model_DatetimeHelper::dateToday();
				$timeNow = Model_DatetimeHelper::timeNow();
			
				$shopCode = $_POST['shop_code'];

				$brand = $_POST['mobile_brand'];
				$model = $_POST['type_device'];
				if(!empty($_POST['mobile_model_other'])){
					$model = $_POST['mobile_model_other'];
				}
				$imei = $_POST['mobile_imei'];
				$partsSelection = "parts";
				$repairType = $_POST['repair_type'];
				
				
				$cname = $_POST['cust_name'];
				$cphone = $_POST['cust_phone'];
				$staffName = $_POST['staff_name'];
				$warrTerm = 7;

				if($shopCode == 'ADPC' || $shopCode == 'CLPC' || $shopCode == 'WLIC'){
 					date_default_timezone_set('Australia/Adelaide');
 					$dateToday = Model_DatetimeHelper::dateToday();
 					$timeNow = Model_DatetimeHelper::timeNow();
 					
					$repairJob->addQuickJob($newJobID, $shopCode, $dateToday, $timeNow, $brand, $model, $imei, $partsSelection, $repairType, $cname, $cphone,$staffName ,$warrTerm);

 				}else{
					$repairJob->addQuickJob($newJobID, $shopCode, $dateToday, $timeNow, $brand, $model, $imei, $partsSelection, $repairType, $cname, $cphone,$staffName ,$warrTerm);
 				}
			
				if($model == "iPod Touch 3" || $model=="iPod Touch 4" || $model=="iPod Touch 5" || $model=="iPod Touch 6" || $model=="iPad 2" || $model=="iPad 3" || $model=="iPad 4" || $model=="iPad 5" || $model=="iPad Mini"  || $model=="iPad Air" || $repairType == 'Back Cover'){
					$repairJob->updateOnScreenImei($newJobID, $imei);
				}

				$idQuoteChoice = 3;
			
				$statusRecord->insertStatus($newJobID,$idQuoteChoice,$dateToday." ".$timeNow,"Simple Job");	
				$transRecord->addTransrecord($newJobID, $shopCode,110, $dateToday, $dateToday.' '.$timeNow,null,"Job Created By ".$staffName,-1);
			
				$this->view->newjobid = $newJobID;
				$this->view->shopcode = $shopCode;
				$this->view->staffname = $staffName;
				$this->view->datetime = $dateToday.$timeNow;
				$this->view->brand = $brand;
				$this->view->model = $model;
				$this->view->imei = $imei;
				$this->view->partsselection = $partsSelection;
				$this->view->repairtype = $repairType;
				$this->view->issuedetail = "";
				$this->view->cname = $cname;
				$this->view->cemail = "";
				$this->view->cphone = $cphone;
				$this->view->cmobile = "";
				$this->view->quotechoice = "Waiting Payment";
				$this->view->price = "N/A";
				$this->view->invoice = "";
				$this->view->passcode = "N/A";
				$this->view->color = "";
				$this->view->pickupdetail = "";
				$this->view->warrTerm = $warrTerm;
				$this->view->extWarr = "";
				$this->view->warrPrice = "";
			
			}
		}
		
		/**
		 * API function for print quick form job invoice 
		 */
		public function quickformReprintAction(){
			$idJob = $this->_getParam("JobId");
			$repairJob = new Model_DbTable_Repairjob();
			$jobDetail = $repairJob->getJob($idJob);
			$this->view->newjobid = $jobDetail['id_job'];
			$this->view->shopcode = $jobDetail['shop_code'];
			$this->view->staffname = "";
			$this->view->datetime = $jobDetail['date_start'].$jobDetail['time_start'];
			$this->view->brand = $jobDetail['mobile_brand'];
			$this->view->model = $jobDetail['mobile_model'];
			$this->view->imei = $jobDetail['mobile_imei'];
			$this->view->partsselection = $jobDetail['parts_selection'];
			$this->view->repairtype = $jobDetail['repair_type'];
			$this->view->issuedetail = "";
			$this->view->cname = $jobDetail['customer_name'];
			$this->view->cemail = "";
			$this->view->cphone = $jobDetail['customer_phone'];
			$this->view->cmobile = "";
			$this->view->quotechoice = "Waiting Payment";
			$this->view->price = $jobDetail['quot_price'];
			$this->view->invoice = "";
			$this->view->passcode = $jobDetail['mobile_passcode'];
			$this->view->color = "";
			$this->view->pickupdetail = "";
			$this->view->warrTerm = $jobDetail['warranty_term'];
			$this->view->extWarr = "";
			$this->view->warrPrice = "";
			
			
		}
		
		/**
		 * This page is part of the device tracking system 
		 * this system is to using to record who last own the mobile phone
		 * or job ID 
		 * 
		 */
		public function transferMobileAction(){
			
			$shop = $this->_getParam("shop");
			
			// Check Password 
			$transRecord = new Model_DbTable_Pr_Transrecord();
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();

			$repaircenter = unserialize(ARR_RCENTER_MAPPING);
			$repairJob = new Model_DbTable_Repairjob();
			$lastStatusList = new Model_DbTable_Repairstatusrecord();
			$pStock = new Model_DbTable_Phonestocktake();
			
			$thisMonday = Model_DatetimeHelper::getThisWeekMonday();
			$searchResult = $repairJob->listUnfinishedJobByShop($shop);
			
			$shopId = $repaircenter[$shop];
			if($shopId < 10){
				$shopId = "0".$shopId;
			}
			
			$orderNo = "PH".$shopId.Model_DatetimeHelper::getThisWeekMonday("");
				
			$this->view->errorFlag = true;
			
			
			
			$jobList = array();
			foreach ($searchResult as $k => $v){
				$theLastStatus = $lastStatusList->getLastStatus($v['id_job']);
			
				if($theLastStatus[0]['id_status'] == $v['id_status'] and $theLastStatus[0]['time_record'] == $v['time_record'] && $v['is_qf'] != 1){
					$jobList[] = $v;
				}
			}
			$this->view->scanList = $jobList;

			
				
				
			if(isset($_POST['button'])){
	
				$idLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['password']));
			
				if($idLine){
					$jobList = array();
					foreach($_POST['id_job'] as $k => $v){
						if(!empty($v)){
						
						if($idLine['id'] == 110){
							$transRecord->addTransrecord($v, $shop, $idLine['id'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(),8,$_POST['comment'][$k], 0);
						}else{
							$transRecord->addTransrecord($v, $shop, $idLine['id'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(),12,$_POST['comment'][$k], 0);
						}
						$tmpArr['jobId'] = $v;
						$tmpArr['shop'] = $shop;
						$tmpArr['comment']  = $_POST['comment'][$k];	
						$this->view->errorFlag = false;
						$this->view->staffName = $idLine['ni'];
						$jobList[] = $tmpArr;
						}
					}
					$this->view->jobList = $jobList;
				}else{
					$this->view->errorFlag = true;
					echo "<h1>Incorrect Password, Please Click Back And Try Again.</h1>";
				}
			}
				
			
			
				
		}
	
		/**
		 * This is the link in the status page to check mobile phone's transfer history
		 */
		public function checkTrackingInfoAction(){
			
			$idJob = $this->_getParam("id_job");
			$tRecord = new Model_DbTable_Pr_Transrecord();
			$rList = $tRecord->getJobHistory($idJob);
			
			$stInfo = new Model_DbTable_Roster_Stafflogindetail();
			$arrRes = array();
			
			foreach($rList as $k => $v){
				$tmpArr = $v;
				$stLine = $stInfo->getDetail($v['id_staff']);
				$tmpArr['st_name'] = Model_EncryptHelper::getSslPassword($stLine['n']);
				$tmpArr['nick_name'] = $stLine['ni'];
				$arrRes[] = $tmpArr;
			}
			
			$this->view->arrRes = $arrRes;
			
			
		}
		
		
		/**
		 * This is job close wizard, all required information in one page
		 * 
		 */
		public function closeJobWizardAction(){
			$idJob = $this->_getParam("jobid");
			$shopHead = $this->_getParam('shop');
			$shopmapping = unserialize(ARR_RCENTER_MAPPING);
			$sDetail = new Model_DbTable_Roster_Stafflogindetail();
			$rJob = new Model_DbTable_Repairjob();
			$rStock = new Model_DbTable_Pr_Prstockmovement();
			$rProducts = new Model_DbTable_Pr_Prproducts();
	 		$rBorrow = new Model_DbTable_Pr_Loan();
			$jobRow = $rJob->getJob($idJob);
			
			
			if(isset($_POST['save_record'])){
				if(isset($_POST['invoice']) && !empty($_POST['invoice'])){
					if($jobRow['invoice_no']){
						$rJob->updateInvoice2($idJob,$_POST['invoice']);
						$this->view->invoice1 = $_POST['invoice'];
					}else{
						$rJob->updateInvoice($idJob,$_POST['invoice']);
						$this->view->invoice1 = $_POST['invoice'];
					}
					
				}
				
				
				if(isset($_POST['on_screen_imei']) && !empty($_POST['on_screen_imei'])){
					$rJob->updateOnScreenImei($idJob, $_POST['on_screen_imei']);
				}
				
				if(isset($_POST['tech_password']) && !empty($_POST['tech_password'])){
					$idStaffRow = $sDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($_POST["tech_password"])));
					if($idStaffRow){
						$rJob->updateRepairStaff($idJob, $idStaffRow["id"]);
					}
				}
				
				if(isset($_POST['quote']) && !empty($_POST['quote'])){
					if($jobRow['quot_price'] != 0){
						$rJob->updateQuotePrice($idJob,$_POST['quote'],1);
					}else{
						$rJob->updateQuotePrice($idJob,$_POST['quote'],false);
					}
				}
				
				
				$url = "http://".WEB_IP."/repaircenter/changestatusshop/jobid/".$idJob;
				$this->_redirect($url);
				
			}
			
			
			if(isset($_POST['close_job'])){
				if(isset($_POST['invoice']) && !empty($_POST['invoice'])){
						$rJob->updateInvoice2($idJob,$_POST['invoice']);
				}
				
				$url = "http://".WEB_IP."/repaircenter/changestatusshop/jobid/".$idJob;
				$this->_redirect($url);
			}
			

			if($jobRow){
				
				if($jobRow['repair_staff'] != 0 && is_numeric($jobRow['repair_staff'])){
					$rStaff = $sDetail->getDetail($jobRow['repair_staff']);
					$this->view->repairStaff = $rStaff['ni'];
					
				}
				
				
				if($jobRow['invoice_no']){
					$this->view->invoice1 = $jobRow['invoice_no'];	
				}
				if($jobRow['invoice_no2']){
					$this->view->invoice1 = $jobRow['invoice_no2'];
				}
				
				if($jobRow['on_screen_imei']){
					$this->view->onScreenImei = $jobRow['on_screen_imei'];
				}
				
				$tmprows = $rStock->getPartsRecordByJobId($idJob);
				if(!empty($tmprows)){
					//var_dump($tmprows);
					$partsList = array();
					$i = 0;
					foreach($tmprows as $key => $value){
							
						$rowProduct = $rProducts->getProduct($value['id_product']);
						$partsList[$i]  = "[".$rowProduct['code_product']."] ".$rowProduct['title_product']." ";
						if($value['code_move'] == 2){
							$partsList[$i] .= " x ";
						}
						elseif($value['code_move'] == 7){
							$partsList[$i] .= " x - ";
						}
							
						$partsList[$i] .= $value['qty_product']." has record";
						$i++;
					}
					$this->view->partsRecord = $partsList;
					
				}

				$this->view->mobile_imei = $jobRow['mobile_imei'];
				$this->view->jobId = $jobRow['id_job'];
				$this->view->shophead = $shopHead;
				$this->view->shopId = $shopmapping[$shopHead];
				$this->view->quote = $jobRow['quot_price'];
				
			}
				
					
	
				//

		}
		
		/**
		 * this is in the device pickup wizard 
		 * device pickup wizard is the wiard guide staff what to do 
		 * when customer come to pickup 
		 * this function is not in good use.
		 * this step check if the phone been fixed
		 */
		public function devicePickupStep0Action(){
			
			$this->view->idJob = $this->_getParam("idjob");
			$this->view->shopCode = $this->_getParam("shop");
			$this->view->idRcenter = $this->_getParam("idrc");
			
				
			// missing information
				
		}
		
		/**
		 * This is the device pickup wizard
		 * this step check the Quotation / Invoice / Warranty
		 */
		public function devicePickupStep1Action(){
			
			$idJob = $this->_getParam("idjob");
			$this->view->shopCode = $this->_getParam("shop");
			$this->view->idRcenter = $this->_getParam("idrc");
			$this->view->idJob = $idJob;
			
			$rJob = new Model_DbTable_Repairjob();
			$rJobLine = $rJob->getJob($idJob);
		
			$this->view->quotePrice = $rJobLine['quot_price'];
			$this->view->extWPrice = $rJobLine['warranty_price'];
			
			$onScreenImei = $rJobLine['mobile_imei'];
			$model = $rJobLine['mobile_model'];
			
			if($model == "iPod Touch 3" || $model=="iPod Touch 4" || $model=="iPod Touch 5" || $model=="iPod Touch 6" || $model=="iPad 2" || $model=="iPad 3" || $model=="iPad 4" || $model=="iPad 5" || $model=="iPad Mini"  || $model=="iPad Air" ){
			
				$this->view->mobile_imei = '';
				$this->view->mobile_aid = $onScreenImei;
			}
			else{
				$this->view->mobile_imei = $onScreenImei;
				$this->view->mobile_aid ='';
				
			}
			
			
			
			$this->view->inv1 = $rJobLine['invoice_no'];
			$this->view->inv2 = $rJobLine['invoice_no2'];
			$this->view->inv1Amt = $rJobLine['invoice1_price'];
			$this->view->inv2Amt = $rJobLine['invoice2_price'];
			
			$this->view->warrantyPeriod = $rJobLine['warranty_term'];
			$this->view->extWarranty = $rJobLine['extended_warranty'];
			
			$warrantyDate =  $rJobLine['warranty_term'] +  $rJobLine['extended_warranty']+1;
			$waterDamage = 31;
			$beginDate = Model_DatetimeHelper::dateToday();
				
			$warrantyEnd = Model_DatetimeHelper::adjustDays("add", $beginDate, $warrantyDate);
			$waterEnd = Model_DatetimeHelper::adjustDays("add", $beginDate, $waterDamage);
				
			$this->view->wyEnd = date("D , jS M Y ",strtotime($warrantyEnd));
			$this->view->wrEnd =  date("D , jS M Y ",strtotime($waterEnd));
			
			
			// missing information 
			
		}
		/**
		 * This is the device pickup wizard
		 * This step check IMEI and let staff to print the warranty paper
		 */
		public function devicePickupStep2Action(){

			
			$idJob = $this->_getParam("idjob");
			$this->view->shopCode = $this->_getParam("shop");
			$this->view->idRcenter = $this->_getParam("idrc");
			$this->view->idJob = $idJob;
			$rJob = new Model_DbTable_Repairjob();
			$rJobLine = $rJob->getJob($idJob);
			
			if($_POST){
				//get information 
				//d($_POST);
				$imei = (trim($_POST['mobile_imei'])== '')?trim($_POST['mobile_aid']):trim($_POST['mobile_imei']);
				$rJob->updateOnScreenImei($idJob, $imei);
				$rJob->updateQuotePrice($idJob, $_POST['quote_job'], false);
				$rJob->updateInvoice($idJob, $_POST['inv_no1'],$_POST['inv_amt1']); // with invoice amount 
				$rJob->updateInvoice2($idJob, $_POST['inv_no2'],$_POST['inv_amt2']);
				$rJob->updateExtWarrantyPrice($idJob, $_POST['ext_warranty']);
				// update 
				// change quote , ext warranty, inv1 , inv2, invamt 1,2 				
			}
			$rJobLine = $rJob->getJob($idJob);
			$this->view->warrantyPeriod = $rJobLine['warranty_term'];
			$this->view->extWarranty = $rJobLine['extended_warranty'];
			
			$this->view->deviceDetail = $rJobLine['mobile_brand']." ".$rJobLine['mobile_model']." Color: ".$rJobLine['mobile_color'];
			$this->view->imei = $rJobLine['on_screen_imei'];
			$this->view->serviceDetail = $rJobLine['repair_type'];
			
			$warrantyDate =  $rJobLine['warranty_term'] +  $rJobLine['extended_warranty']+1;
			$waterDamage = 31;
			$beginDate = Model_DatetimeHelper::dateToday();
			
			$warrantyEnd = Model_DatetimeHelper::adjustDays("add", $beginDate, $warrantyDate);
			$waterEnd = Model_DatetimeHelper::adjustDays("add", $beginDate, $waterDamage);
			
			$this->view->wyEnd = date("D , jS M Y ",strtotime($warrantyEnd));
			$this->view->wrEnd =  date("D , jS M Y ",strtotime($waterEnd));
			
			
			// Sign and print 
			
		}
		/**
		 * This is the device pickup wizard
		 * This is the actual page to print the warranty paper
		 */
		public function devicePickupWarrantyAction(){
		//	d($_POST);
			$idJob = $this->_getParam("idjob");
			$this->view->shopCode = $this->_getParam("shop");
			$this->view->idRcenter = $this->_getParam("idrc");
			$this->view->idJob = $idJob;
			
			$rJob = new Model_DbTable_Repairjob();

			
			if($_POST){
				//get information
				//d($_POST);
				$imei = (trim($_POST['mobile_imei'])== '')?trim($_POST['mobile_aid']):trim($_POST['mobile_imei']);
				$rJob->updateOnScreenImei($idJob, $imei);
				$rJob->updateQuotePrice($idJob, $_POST['quote_job'], false);
				$rJob->updateInvoice($idJob, $_POST['inv_no1'],$_POST['inv_amt1']); // with invoice amount
				$rJob->updateInvoice2($idJob, $_POST['inv_no2'],$_POST['inv_amt2']);
				$rJob->updateExtWarrantyPrice($idJob, $_POST['ext_warranty']);
				// update
				// change quote , ext warranty, inv1 , inv2, invamt 1,2
			}
			
			$rJobLine = $rJob->getJob($idJob);

			$sHead = new Model_DbTable_Shoplocation();
			$this->view->shopName = $sHead->getNameByHead($this->view->shopCode);
			$this->view->deviceDetail = $rJobLine['mobile_brand']." ".$rJobLine['mobile_model']." Color: ".$rJobLine['mobile_color'];
			$this->view->imei = $rJobLine['on_screen_imei'];
			$this->view->serviceDetail = $rJobLine['repair_type'];
			//finish the job 
		}
		
		/**
		 *	This is the final step of device pickup after this step 
		 * 	the wizard is complete 
		 */
		public function devicePickupStepFinalAction(){
			
			$this->view->isFixed = $isFix =  $this->_getParam("isfix");
			$this->view->idJob =$idJob =  $this->_getParam("idjob");
			$this->view->shopCode = $this->_getParam("shop");
			$this->view->idRcenter = $this->_getParam("idrc");
			$this->view->nameStaff = '';
			$this->view->pickupComplete = false;
			
			$rJob = new Model_DbTable_Repairjob();
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();
			$rStatus = new Model_DbTable_Repairstatusrecord();
			
			
			$this->view->rDetail = $rJob->getJob($idJob);
			
			if(isset($_POST['btn_complete'])){
				$stLine = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['password']));
				if($stLine){
					$nickName =  $stLine['ni'];
				
					$this->view->pickupComplete = true;
					
					$idStatus = ($isFix)?72:70;
					
					$rStatus->insertStatus($idJob, $idStatus, Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(),$nickName);
					$this->view->nameStaff = $nickName;
				}
				else{
					
					echo "<h1>Incorrect Password , Please Verify Your Password and Try Again!</h1>";
				}
			
			}
			//$rListName = $stLine['ni']."(".Model_EncryptHelper::getSslPassword($stLine['n']).")";			
			
			//
			
		}
		
		/**
		 * After the customer pickup the item and gone 
		 * the staff can now close the job 
		 * since all the info are already in place 
		 * there should be no problem for staff to close the job 
		 * unless they don't want to close the job for reasons
		 * 
		 */
		public function devicePickupStepClosejobAction(){
				
			$this->view->isFixed = $this->_getParam("isfix");
			$this->view->idJob =$idJob =  $this->_getParam("idjob");
			$this->view->shopCode = $this->_getParam("shop");
			$this->view->idRcenter = $this->_getParam("idrc");
				
			$rJob = new Model_DbTable_Repairjob();
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();
				
				
			$this->view->rDetail = $rJob->getJob($idJob);
				
			$rListName = '';
			$rList = $rJob->getRepairStaff($idJob);
				
			if($rList > 0){
				$stLine = $stDetail->getDetail($rList);
				$rListName = $stLine['ni']."(".Model_EncryptHelper::getSslPassword($stLine['n']).")";
			}
			$this->view->rListName = $rListName;
			$rMove = new Model_DbTable_Pr_Prstockmovement();
			$rMList = $rMove->getPartsRecordByJobId($idJob);
			$rProduct = new Model_DbTable_Pr_Prproducts();
		
			$arrRes = array();
			$arrPartUsded = array();
			if(!empty($rMList)){
		
				foreach($rMList as $k => $v){
					if($v['code_move'] == 2 || $v['code_move'] == 7 ){
						$rPline = $rProduct->getProduct($v['id_product']);
						$qty = ($v['code_move'] == 2)?$v['qty_product']:-$v['qty_product'];
						$arrRes[] = array($rPline['code_product'],$rPline['title_product'],$qty,$v['date_move']);
						if(isset($arrPartUsded[$rPline['code_product']])){
		
							$arrPartUsded[$rPline['code_product']] += $qty;
						}
						else{
							$arrPartUsded[$rPline['code_product']] = $qty;
						}
					}
				}
		
			}
				
			$this->view->partsDoesUsed = false;
				
			foreach($arrPartUsded as $kp => $vp){
				if($vp >0){
					$this->view->partsDoesUsed = true;
				}
					
			}
				
			$this->view->rMlist = $arrRes;
		
		}
		
		/**
		 * this is short verson of pickup wizard
		 */
		
		public function devicePickupClosejobAction(){
			// check password record who close the job 
			// add close job status accordingly 
			// 80 or 90 
			$shopCode = $this->_getParam("shop");
			if($_POST){
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();

			$rStatus = new Model_DbTable_Repairstatusrecord();
			

				// password scuccess
	
				if($_POST['is_fix']){
					
					$rStatus->insertStatus($_POST['id_job'], 90,Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(), $_POST['name_staff']);
				}	
				else{
					
					$rStatus->insertStatus($_POST['id_job'], 80,Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(),$_POST['name_staff']);
					
				}
				
				$this->_redirect("/repaircenter/mainpage/shop/".$shopCode);// redirect to shop main page
				
				
			}
			
		}
		
		/**
		 * this is short verson of pickup wizard
		 */
		public function pickupDeviceAction(){
			
			$shop = $this->_getParam("shop");
			
			$arrRcenter = unserialize(ARR_RCENTER_MAPPING);
			$idRcenter = $arrRcenter[$shop];
			
			$rJob = new Model_DbTable_Repairjob();
			$rStatus = new Model_DbTable_Repairstatusrecord();
			
			$npList = $rJob->listUnfinishedJobByShop($shop);
			
			
			
			$arrRes = array();
			
			foreach($npList as $k => $v){
				
				$idJob = $v['id_job'];
				$ifPickUp = $rStatus->isJobPickup($idJob);
				$stillOpen = $rStatus->getLastStatus($idJob);
				//d($stillOpen);
				if(isset($stillOpen)){
				if(!$ifPickUp && $stillOpen[0]['id_status'] <80){
					$arrRes[$idJob] = $v;
				} 
				}	
			}
			
			
			$this->view->arrRes = $arrRes;
			
			if($_POST){
				if(trim($_POST['id_job'])!=''){
				
				$jobExist = $rJob->getJob(trim($_POST['id_job']));
				//d($jobExist);
				if(!$jobExist){
					
					echo "<h1>Please input the correct Job ID to procced the Picking up wizard</h1>";
				}
				else{
					
					$ifPickUp = $rStatus->isJobPickup(trim($_POST['id_job']));
					$stillOpen = $rStatus->getLastStatus(trim($_POST['id_job']));
					
					if(!$ifPickUp && $stillOpen[0]['id_status'] <80){
						
						if(isset($_POST['btn_yes'])){
						$url = "/repaircenter/device-pickup-step1/idjob/".trim($_POST['id_job'])."/shop/".$shop."/idrc/".$idRcenter;
						$this->_redirect($url);
						}
						
						if(isset($_POST['btn_no'])){
							$url = "/repaircenter/device-pickup-step-final/idjob/".trim($_POST['id_job'])."/shop/".$shop."/idrc/".$idRcenter."isfix/no";
							$this->_redirect($url);
						}
						
					}
					else{
							
						echo "<h1>The Job ID has been pickup or has been closed , you should not do it again</h1>";
					}
					
					
				}
				

				}
				else{
					echo "<h1>You Must Input The Job ID</h1>";
				}
			
			}
			
		}
		
}
?>